From a684f314ab18562194ce5cd45eeda81afaebd5ad Mon Sep 17 00:00:00 2001 From: Mihail Date: Fri, 27 Nov 2015 15:48:25 +0200 Subject: [PATCH] add adjustRowToKeys function --- lib/ParserValidator.php | 11 +++++++++++ lib/TableParser.php | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------- 2 files changed, 68 insertions(+), 35 deletions(-) create mode 100644 lib/ParserValidator.php diff --git a/lib/ParserValidator.php b/lib/ParserValidator.php new file mode 100644 index 0000000..923c576 --- /dev/null +++ b/lib/ParserValidator.php @@ -0,0 +1,11 @@ +empty_lines_quantity ) { + while ($empty_lines < $this->empty_lines_quantity) { // прочтем строку из файла $this->readRow(); - if ( $this->isEmptyRow() ) { + if ($this->isEmptyRow()) { //счетчик пустых строк //CustomVarDamp::dump($this->current_row_number); $empty_lines++; @@ -76,21 +77,24 @@ abstract class TableParser extends Parser { } // уберем пустые колонки из ряда - $this->filterRow(); + if ($this->keys === NULL) { + $this->filterRow(); + } + - $this->adjustRowToSettings( ); + $this->adjustRowToSettings(); // строка не пустая, имеем прочитанный массив значений $this->current_row_number++; // для первой строки утановим ключи из заголовка - if ( !$this->setKeysFromHeader() ) { + if (!$this->setKeysFromHeader()) { $this->setResult(); } // если у нас установлен лимит, при его достижении прекращаем парсинг - if ( $this->isLastLine() ) + if ($this->isLastLine()) break; // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД @@ -99,6 +103,7 @@ abstract class TableParser extends Parser { } } + /** * определяет первую значимую строку, * считывается файл пока в нем не встретится строка с непустыми колонками @@ -107,12 +112,12 @@ abstract class TableParser extends Parser { */ protected function shiftToFirstValuableLine() { - do { + do { $this->current_row_number++; $this->readRow(); - } while( $this->isEmptyRow() ); + } while ($this->isEmptyRow()); // @todo - сделать опционально // код для того что бы парсить первую строку, закомментировано как предполагается что первая значимая строка это заголовок @@ -123,59 +128,76 @@ abstract class TableParser extends Parser { /** * @return array - одномерный массив результата парсинга строки */ - protected function adjustRowToSettings( ) + protected function adjustRowToSettings() { - // если есть заголовок, то перед конвертацией его нужно назначить - if ( $this->keys !== NULL ) { - - if (count($this->keys) !== count($this->row)) { - throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}. - Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными"); - } - - $this->row = array_combine($this->keys, $this->row); - } + // если есть заголовок, то перед конвертацией его нужно назначить + if ($this->keys !== NULL) { + // adjust row to keys + $this->adjustRowToKeys(); + // назначим заголовок + $this->row = array_combine($this->keys, $this->row); + } - // попытаемся конвертировать прочитанные значения согласно конфигурации котнвертера значений - $this->row = $this->convert($this->row); + // попытаемся конвертировать прочитанные значения согласно конфигурации котнвертера значений + $this->row = $this->convert($this->row); - // обрежем массив к первой значимой колонке - if ( $this->first_column ) { + // обрежем массив к первой значимой колонке + if ($this->first_column) { - $this->row = array_slice($this->row, $this->first_column); + $this->row = array_slice($this->row, $this->first_column); - } + } } - protected function setKeysFromHeader(){ - if ( $this->has_header_row ) { + protected function setKeysFromHeader() + { + if ($this->has_header_row) { // в файле есть заголовок, но он еще не назначен - назначим if ($this->keys === NULL) { - $this->keys = array_values( $this->row ); + $this->keys = array_values($this->row); return true; } } return false; } - protected function filterRow(){ + protected function filterRow() + { // если есть заголовок - все значения нужны, не фильтруем - if ( $this->has_header_row || !is_array( $this->row ) ) { + if ($this->has_header_row || !is_array($this->row)) { return; } - $this->row = array_filter( $this->row, function($val){ + $this->row = array_filter($this->row, function ($val) { return !$this->isEmptyColumn($val); }); } - protected function isLastLine(){ + protected function isLastLine() + { - if ( ( $this->last_line ) && ( $this->current_row_number > $this->last_line ) ) { + if (($this->last_line) && ($this->current_row_number > $this->last_line)) { return true; } return false; } + protected function adjustRowToKeys() + { + //уберем из ряда те колонки которых нет в ключах + $this->row = array_intersect_key($this->row, $this->keys); + + $keys_count = count($this->keys); + $column_count = count($this->row); + if ($keys_count != $column_count) { + // найдем колонки которых нет в ряде но есть ключах + $arr_diff = array_diff_key($this->keys, $this->row); + foreach ($arr_diff as $key => $value) { + // колонки которых нет в ряде но есть ключах, добавим их с пустым значением + $this->row[$key] = ''; + } + } + } + } \ No newline at end of file -- libgit2 0.21.4