領収証発行サービス
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.1KB

  1. <?php
  2. namespace App\Files;
  3. use Illuminate\Support\Collection;
  4. use Illuminate\Support\Facades\Storage;
  5. use Illuminate\Support\Str;
  6. use LogicException;
  7. class CsvFile extends TmpFile
  8. {
  9. const ENCODE_UTF8 = "UTF8";
  10. const ENCODE_SJIS = "SJIS";
  11. public function __construct(
  12. protected array $headers = [],
  13. protected string $encode = self::ENCODE_UTF8
  14. ) {
  15. parent::__construct();
  16. if (!in_array($encode, [static::ENCODE_UTF8, static::ENCODE_SJIS])) {
  17. throw new LogicException("エンコード指定不正:" . $encode);
  18. }
  19. if (count($headers) !== 0) {
  20. $this->addLine($headers);
  21. }
  22. }
  23. public function addLine(array|Collection $row)
  24. {
  25. $str = "";
  26. foreach ($row as $col => $val) {
  27. if ($str !== "") {
  28. $str .= ",";
  29. }
  30. $str .= $val;
  31. }
  32. if ($this->encode === static::ENCODE_SJIS) {
  33. $str = $this->toSjis($str);
  34. }
  35. $this->append($str);
  36. }
  37. private function toSjis(string $source): string
  38. {
  39. return mb_convert_encoding($source, "SJIS", "UTF8");
  40. }
  41. }