diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 7854d4f..3a386b8 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -52,6 +52,8 @@ class ParserController extends BaseController public function actionIndex($mode = 0) { +// $path = 'common\components\parsers\CustomConverter'; +// CustomVarDamp::dumpAndDie(new $path()); $model = new UploadFileParsingForm(); // установим режим, 0 - ручная загрузка, 1 - автозагрузка $model->mode = $mode; @@ -81,7 +83,6 @@ class ParserController extends BaseController try { $files_model->save(); } catch (ErrorException $e) { - // CustomVarDamp::dump($e->getMessage()); throw $e; } // получим id только что записанной записи - его запишем в название файла diff --git a/backend/models/UploadFileParsingForm.php b/backend/models/UploadFileParsingForm.php index 165d7a1..aeac2d0 100644 --- a/backend/models/UploadFileParsingForm.php +++ b/backend/models/UploadFileParsingForm.php @@ -71,12 +71,14 @@ class UploadFileParsingForm extends Model public function readFile( $options = [] ){ $data = Yii::$app->multiparser->parse( $this->file_path, $options ); - if( !is_array( $data ) ){ + CustomVarDamp::dumpAndDie($data); + if( !is_array( $data ) || count($data) == 0 ){ throw new ErrorException("Ошибка чтения из файла прайса {$this->file_path}"); } // файл больше не нужен - данные прочитаны и сохранены в кеш -// if( file_exists($this->file_path) ) -// unlink($this->file_path); + if( file_exists($this->file_path) ) + //@ todo - перестало работать - нет доступа на удалениев этом сеансе, в следующем - файл удаляется - разобраться + //unlink( $this->file_path ); return $data; } diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index 8f2382f..704b901 100644 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -14,7 +14,6 @@ 'hasHeaderRow' => true, 'converter_conf' => [ 'class' => ' common\components\parsers\CustomConverter', - 'hasKey' => 1, 'configuration' => ["string" => 'DESCR', "float" => 'PRICE', "brand" => 'BRAND', @@ -54,21 +53,40 @@ ['console' => ['class' => 'yii\multiparser\XmlParser', 'node' => 'Товар', + 'hasHeaderRow' => true, + 'keys' => [ + "BRAND" => 'Производитель', + "ARTICLE"=> 'Код', + "PRICE" => 'Розница', + "DESCR" => 'Наименование', + "BOX" => 'Колво', + "ADD_BOX"=> 'Ожидаемое', + "GROUP" => 'Группа' + ], 'converter_conf' => [ - 'class' => ' common\components\parsers\CustomConverter', - 'hasKey' => 1, + 'class' => 'common\components\parsers\CustomConverter', 'configuration' => ["details" => [] ],], ], - 'basic_column' => [ - "BRAND" => 'Производитель', - "ARTICLE"=> 'Код', - "PRICE" => 'Розница', - "DESCR" => 'Наименование', - "BOX" => 'Колво', - "ADD_BOX"=> 'Ожидаемое', - "GROUP" => 'Группа' - ], + 'web' => + ['class' => 'yii\multiparser\XmlParser', + 'node' => 'Товар', + 'hasHeaderRow' => true, + 'keys' => [ + "BRAND" => 'Производитель', + "ARTICLE"=> 'Код', + "PRICE" => 'Розница', + "DESCR" => 'Наименование', + "BOX" => 'Колво', + "ADD_BOX"=> 'Ожидаемое', + "GROUP" => 'Группа' + ], + 'converter_conf' => [ + 'class' => 'common\components\parsers\CustomConverter', + 'configuration' => ["details" => [] + ],], + ], ], + ]; diff --git a/vendor/yiisoft/multiparser/CsvParser.php b/vendor/yiisoft/multiparser/CsvParser.php index 73acf1e..0d28a0b 100644 --- a/vendor/yiisoft/multiparser/CsvParser.php +++ b/vendor/yiisoft/multiparser/CsvParser.php @@ -18,7 +18,7 @@ class CsvParser extends Parser public $hasHeaderRow = false; /** @var array - массив с заголовком, * если не указан и установлено свойство $hasHeaderRow - будет определен автоматически */ - public $keys; + // public $keys; - определен в родительском классе /** @var экземляр SplFileObject читаемого файла */ public $file; @@ -66,11 +66,6 @@ class CsvParser extends Parser $this->shiftToFirstValuableLine(); } - if ($this->hasHeaderRow) { - // если у файла есть заголовок, то в результате имеем ассоциативный массив - $this->converter_conf['hasKey'] = 1; - } - parent::setup(); } diff --git a/vendor/yiisoft/multiparser/ObjectCreator.php b/vendor/yiisoft/multiparser/ObjectCreator.php index c00d7de..ae426ab 100644 --- a/vendor/yiisoft/multiparser/ObjectCreator.php +++ b/vendor/yiisoft/multiparser/ObjectCreator.php @@ -14,7 +14,7 @@ use common\components\CustomVarDamp; class ObjectCreator { public static function build( array $configuration ){ if ( isset( $configuration['class'] ) ) { - $class = $configuration['class']; + $class = trim( $configuration['class'] ); unset( $configuration['class'] ); } else{ throw new \ErrorException('Error configuration - undefined class'); diff --git a/vendor/yiisoft/multiparser/Parser.php b/vendor/yiisoft/multiparser/Parser.php index bba4a7f..4db7fe1 100644 --- a/vendor/yiisoft/multiparser/Parser.php +++ b/vendor/yiisoft/multiparser/Parser.php @@ -13,6 +13,11 @@ abstract class Parser public $converter_conf = []; protected $converter = NULL; + /** @var array - массив с заголовком, + * */ + public $keys = NULL; + public $hasHeaderRow = false; + public function setup() { $this->setupConverter(); @@ -20,6 +25,11 @@ abstract class Parser protected function setupConverter() { + if ($this->hasHeaderRow) { + // если у файла есть заголовок, то в результате имеем ассоциативный массив + $this->converter_conf['hasKey'] = 1; + } + $converter = ObjectCreator::build( $this->converter_conf ); if ( $converter instanceof ConverterInterface ) { diff --git a/vendor/yiisoft/multiparser/XmlParser.php b/vendor/yiisoft/multiparser/XmlParser.php index 216ab88..4a48938 100644 --- a/vendor/yiisoft/multiparser/XmlParser.php +++ b/vendor/yiisoft/multiparser/XmlParser.php @@ -9,6 +9,9 @@ namespace yii\multiparser; +use common\components\CustomVarDamp; +use common\components\CustomArrayHelper; + class XmlParser extends Parser{ /** @var экземляр SplFileObject читаемого файла */ public $file; @@ -17,21 +20,13 @@ class XmlParser extends Parser{ public function read() { $file = $this->file; - $result = self::xmlToArray( $file->getPathname() ); + $result = $this->xmlToArray( $file->getPathname() ); + if ( isset($this->node) ) { - $result = $result[$this->node]; - } - //@todo переделать на универсальный способ, а для фрейма создать отдельный класс -// $key_column = \Yii::$app->multiparser->getConfiguration('xml','basic_column'); -// $key_column = array_flip($key_column); -// -// $result = \Yii::$app->multiparser->convertToAssocArray($result, $key_column); -// foreach ( $result as &$value ) { -// if (is_array($value)) { -// $value = \Yii::$app->multiparser->convertByConfiguration( $value, $this->converter_conf ); -// } -// } + $result = $result[ $this->node ]; + + } return $result; } @@ -44,12 +39,12 @@ class XmlParser extends Parser{ * @param string $file_path * @return array */ - protected static function xmlToArray( $file_path ) { + protected function xmlToArray( $file_path ) { try { $xml = new \SimpleXMLElement( $file_path, 0, true ); //\common\components\CustomVarDamp::dumpAndDie($xml->children()->children()); - $result = self::recursiveXMLToArray( $xml ); + $result = $this->recursiveXMLToArray( $xml ); } catch(Exception $ex) { throw $ex; @@ -66,26 +61,60 @@ class XmlParser extends Parser{ * * @return mixed */ - protected static function recursiveXMLToArray($xml) { - if(is_object($xml) && get_class($xml) == 'SimpleXMLElement') { + protected function recursiveXMLToArray($xml) { + if( $xml instanceof \SimpleXMLElement ) { $attributes = $xml->attributes(); - foreach($attributes as $k => $v) { - if($v) $a[$k] = (string) $v; + + foreach( $attributes as $key => $value ) { + if( $value ) { + $attribute_array[$key] = (string) $value; + } } - $x = $xml; + $previous_xml = $xml; $xml = get_object_vars($xml); } - //\common\components\CustomVarDamp::dump($xml); if(is_array($xml)) { - if(count($xml) == 0) return (string) $x; // for CDATA + + if( count($xml) == 0 ) + return (string) $previous_xml; // for CDATA + foreach($xml as $key => $value) { - $r[$key] = self::recursiveXMLToArray($value); + $row[$key] = $this->recursiveXMLToArray($value); + } + if ( is_string($value) ) { + // дошли до конца рекурсии + // преобразуем ряд согласно конфигурации + if ( $this->keys !== NULL ) { + + // назначим ключи из конфигурации, согласно массиву $keys + $row = $this->compareArrayWithKeys( $row ); + } + $row = $this->convert( $row ); + } - if(isset($a)) $r['@'] = $a; // Attributes - return $r; + + + if( isset( $attribute_array ) ) + $row['@'] = $attribute_array; // Attributes + + return $row; } - //\common\components\CustomVarDamp::dumpAndDie($xml); return (string) $xml; } + + /** + * @param array $value_arr - текущий ряд, массив, которому нужно назначить конфигурационные ключи ($keys) + * @return array + */ + protected function compareArrayWithKeys( array $value_arr ){ + $res = $this->keys; + foreach ( $this->keys as $key => $value ) { + if ( array_key_exists( $value, $value_arr ) ) { + $res[$key] = $value_arr[$value]; + } + } + return $res; + } + } \ No newline at end of file -- libgit2 0.21.4