lucajackal85 /
Copycat
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Jackal\Copycat\Reader; |
||
| 4 | |||
| 5 | use SplFileObject; |
||
| 6 | use Symfony\Component\OptionsResolver\OptionsResolver; |
||
| 7 | |||
| 8 | /** |
||
| 9 | * Class CSVFileReader |
||
| 10 | * @package Jackal\Copycat\Reader |
||
| 11 | */ |
||
| 12 | class CSVFileReader extends BaseReader |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * @var SplFileObject |
||
| 16 | */ |
||
| 17 | protected $fileObject; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @var array |
||
| 21 | */ |
||
| 22 | protected $options; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * CSVFileReader constructor. |
||
| 26 | * @param SplFileObject $fileObject |
||
| 27 | * @param array $options |
||
| 28 | */ |
||
| 29 | public function __construct(SplFileObject $fileObject, array $options = []) |
||
| 30 | { |
||
| 31 | $resolver = new OptionsResolver(); |
||
| 32 | $resolver->setDefaults([ |
||
| 33 | 'delimiter' => ',', |
||
| 34 | 'enclosure' => '"', |
||
| 35 | 'header' => true, |
||
| 36 | ]); |
||
| 37 | |||
| 38 | $this->options = $resolver->resolve($options); |
||
| 39 | |||
| 40 | $this->fileObject = $fileObject; |
||
| 41 | |||
| 42 | $headers = []; |
||
| 43 | if ($this->options['header']) { |
||
| 44 | $headers = $this->readCurrentRow(); |
||
| 45 | } |
||
| 46 | |||
| 47 | while (($data = $this->readCurrentRow()) != false) { |
||
| 48 | //skip empty rows |
||
| 49 | if($data == [null]){ |
||
| 50 | continue; |
||
| 51 | } |
||
| 52 | if ($headers) { |
||
| 53 | $this->addItem(array_combine($headers, $data)); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 54 | } else { |
||
| 55 | $this->addItem($data); |
||
| 56 | } |
||
| 57 | } |
||
| 58 | } |
||
| 59 | |||
| 60 | protected function readCurrentRow() |
||
| 61 | { |
||
| 62 | return $this->fileObject->fgetcsv($this->options['delimiter'], $this->options['enclosure']); |
||
| 63 | } |
||
| 64 | } |
||
| 65 |