diff --git a/lib/CsvParser.php b/lib/CsvParser.php index 1a191e7..05b57c2 100644 --- a/lib/CsvParser.php +++ b/lib/CsvParser.php @@ -34,6 +34,8 @@ class CsvParser extends TableParser { parent::read(); + $this->cleanUp(); + return $this->result; } @@ -54,6 +56,10 @@ class CsvParser extends TableParser $j = 0; for ($i = 1; $i <= count( $this->row ); $i++) { + if ( !isset( $this->row[ $i - 1 ] ) ) { + continue; + } + if ( $this->isEmptyColumn( $this->row[$i - 1] ) ) { $j++; } @@ -70,4 +76,8 @@ class CsvParser extends TableParser protected function isEmptyColumn( $val ){ return $val == ''; } + + protected function setResult( ){ + $this->result[] = $this->row; + } } \ No newline at end of file diff --git a/lib/Parser.php b/lib/Parser.php index f0405f1..4315c10 100644 --- a/lib/Parser.php +++ b/lib/Parser.php @@ -17,6 +17,9 @@ abstract class Parser public $converter_conf = []; protected $converter = NULL; + /** @var экземляр SplFileObject читаемого файла */ + public $file; + /** * @var array - результирующий массив с отпарсенными значениями */ @@ -28,9 +31,15 @@ abstract class Parser /** @var bool имеет ли файл заголовок который будет установлен ключами возвращемого массива*/ public $has_header_row = false; + /* + *если есть ключи, то колонки с пустыми значениями будут пропускаться (из ряда такие значения будут удаляться), + * например если в файле вторая колонка пустая то она будет удалена + * если есть $has_header_row - то первая значимая строка становится ключами, но пустые колонки не удаляются из ряда + * например если в файле вторая колонка пустая то ей будет назначен соответсвующий ключ (второй) из первой строки + * все описаное выше реализуется в дочернем семействе классов TableParser в методе filterRow() + * для xml происходит просто сопоставление переданных ключей с прочитанными + */ - /** @var экземляр SplFileObject читаемого файла */ - public $file; @@ -78,4 +87,14 @@ abstract class Parser return $arr; } + + protected function cleanUp( ) + { + unset( $this->file ); + unset( $this->converter ); + unset( $this->converter_conf ); + + } + + } \ No newline at end of file diff --git a/lib/ParserHandler.php b/lib/ParserHandler.php index e7d5f18..6658962 100644 --- a/lib/ParserHandler.php +++ b/lib/ParserHandler.php @@ -60,24 +60,12 @@ class ParserHandler public function run() { - $result = []; - if (count($this->custom_configuration)) { + $parser = $this->createObjectByConfiguration( $this->custom_configuration ); - $parser = $this->createObjectByConfiguration($this->custom_configuration); - - try { - - $parser->setup(); - $result = $parser->read(); - - } catch (\ErrorException $e) { - - echo $e->getMessage(); - - } - - } + $parser->setup(); + $result = $parser->read(); + unset($this->fileObject); return $result; } @@ -106,6 +94,10 @@ class ParserHandler { return ObjectCreator::build($configuration); } + + + + } diff --git a/lib/TableParser.php b/lib/TableParser.php index 33ac7ac..748da48 100644 --- a/lib/TableParser.php +++ b/lib/TableParser.php @@ -94,11 +94,8 @@ abstract class TableParser extends Parser { // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД $empty_lines = 0; - - } - } /** * определяет первую значимую строку, @@ -131,7 +128,8 @@ abstract class TableParser extends Parser { if ( $this->keys !== NULL ) { if (count($this->keys) !== count($this->row)) { - throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными"); + throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}. + Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными"); } $this->row = array_combine($this->keys, $this->row); @@ -161,15 +159,13 @@ abstract class TableParser extends Parser { } protected function filterRow(){ - // если есть заголовок или ключи - все значения нужны, не фильтруем - if ( $this->has_header_row || $this->keys !== NULL ) { + // если есть заголовок - все значения нужны, не фильтруем + if ( $this->has_header_row || $this->row === NULL ) { return; } - // CustomVarDamp::dump( $this->row); $this->row = array_filter( $this->row, function($val){ return !$this->isEmptyColumn($val); }); - //CustomVarDamp::dump( $this->row); } protected function isLastLine(){ diff --git a/lib/XlsxParser.php b/lib/XlsxParser.php index cf5e88d..ed28043 100644 --- a/lib/XlsxParser.php +++ b/lib/XlsxParser.php @@ -62,18 +62,13 @@ class XlsxParser extends TableParser { $this->current_node = $xml->sheetData->row; $this->current_node->rewind(); if ( $this->current_node->valid() ) { - parent::read(); - } - } - } - + $this->cleanUp(); if ( $this->active_sheet ) { - // в настройках указан конкретный лист с которогшо будем производить чтение, поэтому и возвращаем подмассив return $this->result[ $this->current_sheet ]; }else{ @@ -90,7 +85,6 @@ class XlsxParser extends TableParser { throw new \Exception( 'Ошибка создания временного каталога - ' . $this->path_for_extract_files ); } - $zip = new \ZipArchive; if ( $zip->open( $this->file->getPathname() ) === TRUE ) { $zip->extractTo( $this->path_for_extract_files . '/' ); @@ -226,9 +220,16 @@ class XlsxParser extends TableParser { } } - function __destruct() + + protected function cleanUp() { + parent::cleanUp(); + unset($this->strings_arr); + unset($this->sheets_arr); + unset($this->current_node); + $this->deleteExtractFiles(); + } diff --git a/lib/XmlParser.php b/lib/XmlParser.php index a384e72..d021dc1 100644 --- a/lib/XmlParser.php +++ b/lib/XmlParser.php @@ -24,16 +24,17 @@ class XmlParser extends Parser{ } + $this->cleanUp(); return $result; } /** * Converts an XML string to a PHP array - * - * @uses recursiveXMLToArray() - * @param string $file_path - * @return array + * @param $file_path + * @return mixed + * @throws Exception + * @throws \Exception */ protected function xmlToArray( $file_path ) { diff --git a/lib/YiiMultiparser.php b/lib/YiiMultiparser.php index 38e6cd0..886e7fe 100644 --- a/lib/YiiMultiparser.php +++ b/lib/YiiMultiparser.php @@ -17,6 +17,7 @@ class YiiMultiparser extends Component{ public $configuration; public $parserHandler; +public $filePath; public function init() { @@ -29,6 +30,7 @@ public $parserHandler; public function parse( $filePath, $options = [] ){ + $this->filePath = $filePath; $this->parserHandler->setup( $filePath, $options ); return $this->parserHandler->run(); -- libgit2 0.21.4