From d1fac7a9ab175babccfe47e9a448528b154db928 Mon Sep 17 00:00:00 2001 From: Mihail Date: Tue, 27 Oct 2015 13:59:34 +0200 Subject: [PATCH] add parsing sheets to xslx parser --- lib/CsvParser.php | 4 ++++ lib/TableParser.php | 28 ++++++++++++++++++++-------- lib/XlsxParser.php | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 97 insertions(+), 19 deletions(-) diff --git a/lib/CsvParser.php b/lib/CsvParser.php index 7ca1b88..6864ea2 100644 --- a/lib/CsvParser.php +++ b/lib/CsvParser.php @@ -72,4 +72,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/TableParser.php b/lib/TableParser.php index 4a7d8f0..da3d689 100644 --- a/lib/TableParser.php +++ b/lib/TableParser.php @@ -53,6 +53,8 @@ abstract class TableParser extends Parser { protected abstract function readRow(); + protected abstract function setResult(); + public function read() { @@ -66,23 +68,26 @@ abstract class TableParser extends Parser { // прочтем строку из файла $this->readRow(); + // уберем пустые колонки из ряда + $this->filterRow(); + if ( $this->isEmptyRow() ) { //счетчик пустых строк + //CustomVarDamp::dump($this->current_row_number); $empty_lines++; continue; } - // уберем пустые колонки из ряда - $this->filterRow(); - - $this->adjustRowToSettings( ); // строка не пустая, имеем прочитанный массив значений $this->current_row_number++; // для первой строки утановим ключи из заголовка - $this->setKeysFromHeader(); + if ( !$this->setKeysFromHeader() ) { + $this->setResult(); + } + // если у нас установлен лимит, при его достижении прекращаем парсинг if ( $this->isLastLine() ) @@ -91,8 +96,7 @@ abstract class TableParser extends Parser { // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД $empty_lines = 0; - $this->result[] = $this->row; - $this->row = []; + } @@ -129,7 +133,7 @@ abstract class TableParser extends Parser { if ( $this->keys !== NULL ) { if (count($this->keys) !== count($this->row)) { - throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_row_number); + throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными"); } $this->row = array_combine($this->keys, $this->row); @@ -152,14 +156,22 @@ abstract class TableParser extends Parser { // в файле есть заголовок, но он еще не назначен - назначим if ($this->keys === NULL) { $this->keys = array_values( $this->row ); + return true; } } + return false; } protected function filterRow(){ + // если есть заголовок или ключи - все значения нужны, не фильтруем + if ( $this->has_header_row || $this->keys !== 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 73dca08..ef2dd12 100644 --- a/lib/XlsxParser.php +++ b/lib/XlsxParser.php @@ -49,36 +49,53 @@ class XlsxParser extends TableParser { public function read() { - - // $this->extractFiles(); + $this->extractFiles(); $this->readSheets(); $this->readStrings(); foreach ( $this->sheets_arr as $sheet ) { //проходим по всем файлам из директории /xl/worksheets/ - + $this->current_sheet = $sheet; $sheet_path = $this->path_for_extract_files . '/xl/worksheets/' . $sheet . '.xml'; if ( file_exists( $sheet_path ) && is_readable( $sheet_path ) ) { $xml = simplexml_load_file( $sheet_path, "SimpleXMLIterator" ); $this->current_node = $xml->sheetData->row; $this->current_node->rewind(); + if ( $this->current_node->valid() ) { - parent::read(); + parent::read(); + + } } } -CustomVarDamp::dumpAndDie($this->$result); - // return $this->$result_arr; + + + if ( $this->active_sheet ) { + + // в настройках указан конкретный лист с которогшо будем производить чтение, поэтому и возвращаем подмассив + return $this->result[ $this->current_sheet ]; + }else{ + return $this->result; + } + } protected function extractFiles () { + $this->path_for_extract_files = $this->path_for_extract_files . session_id(); + if ( !mkdir($this->path_for_extract_files) ) + { + 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 ); + $zip->extractTo( $this->path_for_extract_files . '/' ); $zip->close(); } else { throw new \Exception( 'Ошибка чтения xlsx файла' ); @@ -88,7 +105,7 @@ CustomVarDamp::dumpAndDie($this->$result); protected function readSheets () { if ( $this->active_sheet ) { - $this->sheets_arr[ $this->active_sheet ] = 'Sheet' . $this->active_sheet; + $this->sheets_arr[ ] = 'Sheet' . $this->active_sheet; return; } @@ -125,9 +142,14 @@ CustomVarDamp::dumpAndDie($this->$result); // protected function readRow ( $item, $sheet , $current_row ) protected function readRow ( ) { + $this->row = []; $node = $this->current_node->getChildren(); - - foreach ( $node as $child ) { + if ($node === NULL) { + return; + } + //foreach ( $node as $child ) { + for ( $node->rewind(); $node->valid(); $node->next() ) { + $child = $node->current(); $attr = $child->attributes(); if( isset($child->v) ) { @@ -144,13 +166,20 @@ CustomVarDamp::dumpAndDie($this->$result); } } + // дополним ряд пустыми значениями если у нас ключей больше чем значений + if ( $this->has_header_row && ( count( $this->keys ) > count( $this->row ) ) ) { + $extra_coloumn = count( $this->keys ) - count( $this->row ); + for ( $i = 1; $i <= $extra_coloumn; $i++ ) { + $this->row[] = ''; + } + } $this->current_node->next(); - CustomVarDamp::dump($this->row); } protected function isEmptyRow(){ $is_empty = false; + // CustomVarDamp::dump(count( $this->row ), $this->current_row_number); if ( !count( $this->row ) || !$this->current_node->valid() ) { return true; @@ -175,4 +204,37 @@ CustomVarDamp::dumpAndDie($this->$result); protected function isEmptyColumn( $val ){ return $val == ''; } + + protected function setResult( ){ + $this->result[ $this->current_sheet ][] = $this->row; + } + + protected function deleteExtractFiles () + { + $this->removeDir( $this->path_for_extract_files ); + + } + + protected function removeDir($dir) { + if (is_dir($dir)) { + $objects = scandir($dir); + foreach ($objects as $object) { + if ($object != "." && $object != "..") { + if (filetype($dir."/".$object) == "dir") + $this->removeDir($dir."/".$object); + else + unlink($dir."/".$object); + } + } + reset($objects); + rmdir($dir); + } + } + + function __destruct() + { + $this->deleteExtractFiles(); + } + + } \ No newline at end of file -- libgit2 0.21.4