領収証発行サービス
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.

73 lines
1.7KB

  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, array|null $sortDef = null)
  24. {
  25. if ($sortDef !== null) {
  26. $row = $this->sortColumn($sortDef, $row);
  27. }
  28. $str = "";
  29. foreach ($row as $col => $val) {
  30. if ($str !== "") {
  31. $str .= ",";
  32. }
  33. $str .= $val;
  34. }
  35. if ($this->encode === static::ENCODE_SJIS) {
  36. $str = $this->toSjis($str);
  37. }
  38. $this->append($str);
  39. }
  40. private function toSjis(string $source): string
  41. {
  42. return mb_convert_encoding($source, "SJIS", "UTF8");
  43. }
  44. private function sortColumn(array $sortDef, $data): array
  45. {
  46. $ele = [];
  47. $notFound = Str::uuid();
  48. foreach ($sortDef as $def) {
  49. $ret = data_get($data, $def, $notFound);
  50. if ($ret === $notFound) {
  51. throw new LogicException("存在しない項目:" . $def);
  52. }
  53. $ele[] = $ret;
  54. }
  55. return $ele;
  56. }
  57. }