diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index cbf1acc..7a250dc 100644 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -13,7 +13,8 @@ 'auto_detect_first_line' => true, 'converter_conf' => [ 'class' => ' common\components\parsers\CustomConverter', - 'configuration' => ["string" => 'DESCR', + 'configuration' => ["encode" => 'DESCR', + "string" => 'DESCR', "float" => 'PRICE', "brand" => 'BRAND', "integer" => ['BOX','ADD_BOX'], @@ -72,7 +73,9 @@ 'path_for_extract_files' => \Yii::getAlias('@temp_upload') . '/', 'converter_conf' => [ 'class' => 'common\components\parsers\CustomConverter', - 'configuration' => ["encode" => 'DESCR'],] + 'hasHeaderRow' => true, + 'configuration' => ["string" => []], + ] ], ] ]; diff --git a/vendor/yiisoft/multiparser/Converter.php b/vendor/yiisoft/multiparser/Converter.php index 6865c55..66289c9 100644 --- a/vendor/yiisoft/multiparser/Converter.php +++ b/vendor/yiisoft/multiparser/Converter.php @@ -64,9 +64,19 @@ class Converter implements ConverterInterface public static function convertToString($value) { - $value = self::convertToEncode($value); + $convert_func = function ($value_to_convert) { + return str_replace(array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '~', '`', '"', "'", ' ', '№', '%', ';', ':', '[', ']', '{', '}', '*', '?', '/', '\'', '|', '.', ',', '<', '>', '\\'), '', $value_to_convert); + }; - return str_replace(array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '~', '`', '"', "'", ' ', '№', '%', ';', ':', '[', ']', '{', '}', '*', '?', '/', '\'', '|', '.', ',', '<', '>', '\\'), '', $value); + if( is_string( $value ) ){ + $value = $convert_func( $value ); + } + + if( is_array( $value ) ){ + array_walk( $value, $convert_func ); + } + + return $value; } /** @@ -109,7 +119,7 @@ class Converter implements ConverterInterface $arr_config = $configuration['configuration']; unset($configuration['configuration']); } else { - throw new \ErrorException('Не указан обязательный параметр конфигурационного файла - converter_conf[configuration]'); + throw new \Exception('Не указан обязательный параметр конфигурационного файла - converter_conf[configuration]'); } // проставим аттрибуты из конфига{}{} diff --git a/vendor/yiisoft/multiparser/Parser.php b/vendor/yiisoft/multiparser/Parser.php index 0b60829..283c36f 100644 --- a/vendor/yiisoft/multiparser/Parser.php +++ b/vendor/yiisoft/multiparser/Parser.php @@ -38,9 +38,7 @@ abstract class Parser public function setup() { - $this->setupConverter(); - } protected function setupConverter() @@ -50,13 +48,16 @@ abstract class Parser $this->converter_conf['hasKey'] = 1; } - $converter = ObjectCreator::build( $this->converter_conf ); - if ( $converter instanceof ConverterInterface ) { + if ( $this->converter_conf ) { + $converter = ObjectCreator::build( $this->converter_conf ); + if ( $converter instanceof ConverterInterface ) { - $this->converter = $converter; + $this->converter = $converter; + } } + } public abstract function read(); @@ -68,6 +69,7 @@ abstract class Parser */ protected function convert( $arr ) { + if ($this->converter !== NULL) { $arr = $this->converter->convertByConfiguration( $arr, $this->converter_conf ); diff --git a/vendor/yiisoft/multiparser/TableParser.php b/vendor/yiisoft/multiparser/TableParser.php index c20b3b1..4a7d8f0 100644 --- a/vendor/yiisoft/multiparser/TableParser.php +++ b/vendor/yiisoft/multiparser/TableParser.php @@ -66,13 +66,12 @@ abstract class TableParser extends Parser { // прочтем строку из файла $this->readRow(); - - if ( $this->isEmptyRow() ) { //счетчик пустых строк $empty_lines++; continue; } + // уберем пустые колонки из ряда $this->filterRow(); @@ -84,7 +83,7 @@ abstract class TableParser extends Parser { // для первой строки утановим ключи из заголовка $this->setKeysFromHeader(); - + // если у нас установлен лимит, при его достижении прекращаем парсинг if ( $this->isLastLine() ) break; @@ -93,12 +92,12 @@ abstract class TableParser extends Parser { $empty_lines = 0; $this->result[] = $this->row; + $this->row = []; + } } - - /** * определяет первую значимую строку, * считывается файл пока в нем не встретится строка с непустыми колонками @@ -125,6 +124,7 @@ abstract class TableParser extends Parser { */ protected function adjustRowToSettings( ) { + // если есть заголовок, то перед конвертацией его нужно назначить if ( $this->keys !== NULL ) { @@ -155,11 +155,13 @@ abstract class TableParser extends Parser { } } } + protected function filterRow(){ $this->row = array_filter( $this->row, function($val){ return !$this->isEmptyColumn($val); }); } + protected function isLastLine(){ if ( ( $this->last_line ) && ( $this->current_row_number > $this->last_line ) ) { diff --git a/vendor/yiisoft/multiparser/XlsxParser.php b/vendor/yiisoft/multiparser/XlsxParser.php index 116ac41..73dca08 100644 --- a/vendor/yiisoft/multiparser/XlsxParser.php +++ b/vendor/yiisoft/multiparser/XlsxParser.php @@ -16,15 +16,13 @@ use common\components\CustomVarDamp; * Class XlsxParser * @package yii\multiparser */ -class XlsxParser extends Parser { +class XlsxParser extends TableParser { /** * @var string - путь куда будут распаковываться файлы, если не указанно - во временный каталог сервера */ public $path_for_extract_files = ''; - /** @var bool - имеет ли файл заголовок который будет установлен ключами возвращемого массива*/ - public $hasHeaderRow = false; + /** * @var int - если указано то считывание будет производиться с этого листа, иначе со всех листов @@ -34,11 +32,15 @@ class XlsxParser extends Parser { protected $strings_arr = []; protected $sheets_arr = []; - protected $result_arr = []; + + protected $current_node; + protected $current_sheet; public function setup() { + parent::setup(); + if ( $this->path_for_extract_files == '' ) { $this->path_for_extract_files = sys_get_temp_dir(); } @@ -52,9 +54,23 @@ class XlsxParser extends Parser { $this->readSheets(); $this->readStrings(); - $this->readValues(); - CustomVarDamp::dumpAndDie($this->result_arr); + foreach ( $this->sheets_arr as $sheet ) { + //проходим по всем файлам из директории /xl/worksheets/ + + $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(); + + parent::read(); + + } + + } +CustomVarDamp::dumpAndDie($this->$result); // return $this->$result_arr; } @@ -104,46 +120,59 @@ class XlsxParser extends Parser { } } - protected function readValues () - { - //foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) { - foreach ( $this->sheets_arr as $sheet ) { - //проходим по всем файлам из директории /xl/worksheets/ - //CustomVarDamp::dumpAndDie($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 ); - //по каждой строке - $current_row = 0; - - foreach ( $xml->sheetData->row as $row_values ) { - $this->readRowValues( $row_values, $sheet , $current_row ); - $current_row++; - } - } - } - } - protected function readRowValues ( $item, $sheet , $current_row ) + + // protected function readRow ( $item, $sheet , $current_row ) + protected function readRow ( ) { - $this->result_arr[$sheet][$current_row] = array(); - //по каждой ячейке строки - $cell = 0; - foreach ( $item as $child ) { + $node = $this->current_node->getChildren(); + + foreach ( $node as $child ) { $attr = $child->attributes(); if( isset($child->v) ) { $value = (string)$child->v; }else{ - $value = false; + $value = ''; } if ( isset( $attr['t'] ) ) { - $this->result_arr[$sheet][$current_row][$cell] = $this->strings_arr[ $value ]; + // $this->result_arr[$sheet][$current_row][$cell] = $this->strings_arr[ $value ]; + $this->row[] = $this->strings_arr[ $value ]; }else{ - $this->result_arr[$sheet][$current_row][$cell] = $value; + // $this->result_arr[$sheet][$current_row][$cell] = $value; + $this->row[] = $value; } - $cell++; + } + $this->current_node->next(); + CustomVarDamp::dump($this->row); + } + + protected function isEmptyRow(){ + + $is_empty = false; + + if ( !count( $this->row ) || !$this->current_node->valid() ) { + return true; + } + + $j = 0; + for ($i = 1; $i <= count( $this->row ); $i++) { + + if ( $this->isEmptyColumn( $this->row[$i - 1] ) ) { + $j++; + } + + if ( $j >= $this->min_column_quantity ) { + $is_empty = true; + break; + } + } + + return $is_empty; + } + protected function isEmptyColumn( $val ){ + return $val == ''; } } \ No newline at end of file -- libgit2 0.21.4