|
- <?php
-
- namespace App\Files;
-
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- use LogicException;
-
- class CsvFile extends TmpFile
- {
-
- const ENCODE_UTF8 = "UTF8";
- const ENCODE_SJIS = "SJIS";
-
-
- public function __construct(
- protected array $headers = [],
- protected string $encode = self::ENCODE_UTF8
- ) {
- parent::__construct();
-
- if (!in_array($encode, [static::ENCODE_UTF8, static::ENCODE_SJIS])) {
- throw new LogicException("エンコード指定不正:" . $encode);
- }
-
- if (count($headers) !== 0) {
- $this->addLine($headers);
- }
- }
-
- public function addLine(array|Collection $row)
- {
- $str = "";
- foreach ($row as $col => $val) {
- if ($str !== "") {
- $str .= ",";
- }
-
- $str .= $val;
- }
-
- if ($this->encode === static::ENCODE_SJIS) {
- $str = $this->toSjis($str);
- }
-
- $this->append($str);
- }
-
- private function toSjis(string $source): string
- {
- return mb_convert_encoding($source, "SJIS", "UTF8");
- }
- }
|