<?php
namespace App\Utils\CSV\Reader; abstract class AbstractReader { use \App\Utils\BaseParser\OptionTrait; protected $assocMappings = null; protected $currentLineIndex = null; protected $filePath; public $validator = null; public $formatter = null; public function __construct() { $this->validator = new \App\Utils\CSV\Reader\RowValidator($this); $this->formatter = new \App\Utils\CSV\Reader\RowFormatter($this); } public function __destruct() { $this->closeFile(); } public function openFile(string $filePath) { $this->filePath = $filePath; $this->_openFile($this->filePath); return $this; } public function closeFile() { $this->_closeFile($this->filePath); $this->filePath = null; return $this; } public function setAssocMappings(\App\Utils\CSV\Reader\Row $row) { $this->assocMappings = $row; return $this; } public function getAssocMappings() { return $this->assocMappings; } public function getCurentLineIndex() { return $this->currentLineIndex; } public function next(bool $validate=true) { $row = $this->_next(); if ($row && $this->assocMappings) { $row->setAssocMap($this->assocMappings->getRawFields()); } if ($validate && $row) { $this->validator->validateRow($row); } return $row; } public function nextAll() { $return = []; while ($row = $this->next()) { $return[] = $row->getFields(); } return $return; } public function skipRows(int $numberOfRows=1, bool $validate=true) { while ($numberOfRows--) { $this->next($validate); } return $this; } public function setHeaderRow(\App\Utils\CSV\Reader\Row $row, bool $validate=true) { if ($row && $row->hasData() && $row->trimValues()->countValues() == $row->trimValues()->countValidValues()) { $this->setAssocMappings($row); } if ($this->validator->getExpectedColumns()) { $row->setAssocMap($row->getRawFields()); if ($validate) { $this->validator->validateRow($row); } $row->removeAssocMap(); $this->setAssocMappings($row); } return $this; } public function setExpectedColumns(array $expectedColumns, string $mode='strict') { $this->validator->setExpectedColumns($expectedColumns, $mode); return $this; } public function setColumnFormats(array $columnFormats) { $this->validator->setColumnFormats($columnFormats); $this->formatter->setColumnFormats($columnFormats); return $this; } abstract protected function _openFile($file); abstract protected function _closeFile(); abstract protected function _next(); } 