Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
| Total | |
100.00% |
1 / 1 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
16 / 16 |
| CsvGenerator | |
100.00% |
1 / 1 |
|
100.00% |
2 / 2 |
9 | |
100.00% |
16 / 16 |
| createFile | |
100.00% |
1 / 1 |
7 | |
100.00% |
12 / 12 |
|||
| throws | |
100.00% |
1 / 1 |
2 | |
100.00% |
4 / 4 |
|||
| 1 | <?php |
| 2 | |
| 3 | namespace Qmp\Laravel\FileGenerator\Services\FileGenerator\Generators; |
| 4 | |
| 5 | use Qmp\Laravel\FileGenerator\Services\FileGenerator\Exceptions\BadContentStructureException; |
| 6 | use stdClass; |
| 7 | |
| 8 | class CsvGenerator extends AbstractGenerator |
| 9 | { |
| 10 | /** |
| 11 | * |
| 12 | */ |
| 13 | protected const BOM = [0xEF, 0xBB, 0xBF]; |
| 14 | |
| 15 | /** |
| 16 | * @var array|string[] |
| 17 | */ |
| 18 | protected array $rules = [ |
| 19 | 'type' => 'required|in:csv', |
| 20 | 'content' => 'required' |
| 21 | ]; |
| 22 | |
| 23 | /** |
| 24 | * Undocumented variable |
| 25 | * |
| 26 | * @var array |
| 27 | */ |
| 28 | protected array $options = [ |
| 29 | 'separator' => ',', |
| 30 | 'enclosure' => '"', |
| 31 | 'escape' => "\\", |
| 32 | 'strict' => true, |
| 33 | 'deleteOnError' => true |
| 34 | ]; |
| 35 | |
| 36 | |
| 37 | /** |
| 38 | * Undocumented function |
| 39 | * |
| 40 | * @return void |
| 41 | */ |
| 42 | protected function createFile(): void |
| 43 | { |
| 44 | $this->throws(!is_array($this->config->content)); |
| 45 | |
| 46 | $fp = fopen($this->config->output_path, 'w+'); |
| 47 | fputs($fp, implode('', array_map('chr', self::BOM))); |
| 48 | |
| 49 | $opts = (object) $this->getOptions(); |
| 50 | $colCount = !is_array($this->config->content[0]) ? 1 : count($this->config->content[0]); |
| 51 | |
| 52 | foreach ($this->config->content as $line) { |
| 53 | if (!is_array($line)) { |
| 54 | $line = [$line]; |
| 55 | } |
| 56 | |
| 57 | $this->throws($opts->strict && count($line) !== $colCount, fn() => $opts->deleteOnError ? fclose($fp) && unlink($this->config->output_path) : null); |
| 58 | |
| 59 | fputcsv($fp, $line, $opts->separator, $opts->enclosure, $opts->escape); |
| 60 | } |
| 61 | |
| 62 | fclose($fp); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Undocumented function |
| 67 | * |
| 68 | * @param bool $cond |
| 69 | * @return void |
| 70 | */ |
| 71 | protected function throws(bool $cond, callable $closure = null): self |
| 72 | { |
| 73 | if ($cond) { |
| 74 | call_user_func($closure); |
| 75 | throw new BadContentStructureException($this->config->type); |
| 76 | } |
| 77 | |
| 78 | return $this; |
| 79 | } |
| 80 | } |