Commit 3c4b566f4c39f3f14405d618b4d4d071fde22111
1 parent
90ff40df
add XlsxParser
Showing
11 changed files
with
101 additions
and
35 deletions
Show diff stats
backend/controllers/ParserController.php
| @@ -52,8 +52,6 @@ class ParserController extends BaseController | @@ -52,8 +52,6 @@ class ParserController extends BaseController | ||
| 52 | 52 | ||
| 53 | public function actionIndex($mode = 0) | 53 | public function actionIndex($mode = 0) |
| 54 | { | 54 | { |
| 55 | -// $path = 'common\components\parsers\CustomConverter'; | ||
| 56 | -// CustomVarDamp::dumpAndDie(new $path()); | ||
| 57 | $model = new UploadFileParsingForm(); | 55 | $model = new UploadFileParsingForm(); |
| 58 | // установим режим, 0 - ручная загрузка, 1 - автозагрузка | 56 | // установим режим, 0 - ручная загрузка, 1 - автозагрузка |
| 59 | $model->mode = $mode; | 57 | $model->mode = $mode; |
backend/models/UploadFileParsingForm.php
| @@ -48,7 +48,7 @@ class UploadFileParsingForm extends Model | @@ -48,7 +48,7 @@ class UploadFileParsingForm extends Model | ||
| 48 | return [ | 48 | return [ |
| 49 | ['importer_id', 'required', 'message' => 'Не указан поставщик!' ], | 49 | ['importer_id', 'required', 'message' => 'Не указан поставщик!' ], |
| 50 | ['file', 'required', 'message' => 'Не выбран файл!' ], | 50 | ['file', 'required', 'message' => 'Не выбран файл!' ], |
| 51 | - [['file'], 'file', 'extensions' => ['csv', 'xml'], 'checkExtensionByMimeType'=>false ], | 51 | + [['file'], 'file', 'extensions' => ['csv', 'xlsx'], 'checkExtensionByMimeType'=>false ], |
| 52 | ['importer_id', 'integer','max' => 999999, 'min' => 0 ], | 52 | ['importer_id', 'integer','max' => 999999, 'min' => 0 ], |
| 53 | [['action','delete_prefix', 'delete_price', 'success'], 'boolean', 'except' => 'auto' ], // только для ручной загрузки | 53 | [['action','delete_prefix', 'delete_price', 'success'], 'boolean', 'except' => 'auto' ], // только для ручной загрузки |
| 54 | ['delimiter', 'string', 'max' => 1], | 54 | ['delimiter', 'string', 'max' => 1], |
| @@ -71,7 +71,6 @@ class UploadFileParsingForm extends Model | @@ -71,7 +71,6 @@ class UploadFileParsingForm extends Model | ||
| 71 | public function readFile( $options = [] ){ | 71 | public function readFile( $options = [] ){ |
| 72 | 72 | ||
| 73 | $data = Yii::$app->multiparser->parse( $this->file_path, $options ); | 73 | $data = Yii::$app->multiparser->parse( $this->file_path, $options ); |
| 74 | - CustomVarDamp::dumpAndDie($data); | ||
| 75 | if( !is_array( $data ) || count($data) == 0 ){ | 74 | if( !is_array( $data ) || count($data) == 0 ){ |
| 76 | throw new ErrorException("Ошибка чтения из файла прайса {$this->file_path}"); | 75 | throw new ErrorException("Ошибка чтения из файла прайса {$this->file_path}"); |
| 77 | } | 76 | } |
common/components/PriceWriter.php
| @@ -91,7 +91,7 @@ class PriceWriter | @@ -91,7 +91,7 @@ class PriceWriter | ||
| 91 | try { | 91 | try { |
| 92 | //@todo add transaction | 92 | //@todo add transaction |
| 93 | 93 | ||
| 94 | - if ((int)$this->configuration['delete_price']) { | 94 | + if ( isset($this->configuration['delete_price']) && (int)$this->configuration['delete_price'] ) { |
| 95 | $details_model->delete_price = true; | 95 | $details_model->delete_price = true; |
| 96 | } | 96 | } |
| 97 | //2. попытаемся вставить данные в БД с апдейтом по ключам | 97 | //2. попытаемся вставить данные в БД с апдейтом по ключам |
common/components/parsers/config.php
| @@ -68,25 +68,15 @@ | @@ -68,25 +68,15 @@ | ||
| 68 | 'configuration' => ["details" => [] | 68 | 'configuration' => ["details" => [] |
| 69 | ],], | 69 | ],], |
| 70 | ], | 70 | ], |
| 71 | - 'web' => | ||
| 72 | - ['class' => 'yii\multiparser\XmlParser', | ||
| 73 | - 'node' => 'Товар', | ||
| 74 | - 'hasHeaderRow' => true, | ||
| 75 | - 'keys' => [ | ||
| 76 | - "BRAND" => 'Производитель', | ||
| 77 | - "ARTICLE"=> 'Код', | ||
| 78 | - "PRICE" => 'Розница', | ||
| 79 | - "DESCR" => 'Наименование', | ||
| 80 | - "BOX" => 'Колво', | ||
| 81 | - "ADD_BOX"=> 'Ожидаемое', | ||
| 82 | - "GROUP" => 'Группа' | ||
| 83 | - ], | ||
| 84 | - 'converter_conf' => [ | ||
| 85 | - 'class' => 'common\components\parsers\CustomConverter', | ||
| 86 | - 'configuration' => ["details" => [] | ||
| 87 | - ],], | ||
| 88 | - ], | ||
| 89 | ], | 71 | ], |
| 90 | - | 72 | + 'xlsx' => |
| 73 | + ['web' => | ||
| 74 | + ['class' => 'yii\multiparser\XlsxParser', | ||
| 75 | + 'path_for_extract_files' => \Yii::getAlias('@temp_upload') . '/', | ||
| 76 | + 'converter_conf' => [ | ||
| 77 | + 'class' => 'common\components\parsers\CustomConverter', | ||
| 78 | + 'configuration' => ["encode" => 'DESCR'],] | ||
| 79 | + ], | ||
| 80 | + ] | ||
| 91 | ]; | 81 | ]; |
| 92 | 82 |
console/.gitignore
console/controllers/ParserController.php
| @@ -59,8 +59,7 @@ class ParserController extends Controller | @@ -59,8 +59,7 @@ class ParserController extends Controller | ||
| 59 | } | 59 | } |
| 60 | $data = \Yii::$app->multiparser->parse( $file_path, $parser_config ); | 60 | $data = \Yii::$app->multiparser->parse( $file_path, $parser_config ); |
| 61 | if ( ! $data ) { | 61 | if ( ! $data ) { |
| 62 | - // @todo переделать, что бы ошибка автоматически останавливала сценарий | ||
| 63 | - return false; | 62 | + throw new ErrorException("Ошибка обработки файла прайса!"); |
| 64 | } | 63 | } |
| 65 | 64 | ||
| 66 | $writer = new PriceWriter(); | 65 | $writer = new PriceWriter(); |
| @@ -105,7 +104,7 @@ class ParserController extends Controller | @@ -105,7 +104,7 @@ class ParserController extends Controller | ||
| 105 | ]; | 104 | ]; |
| 106 | 105 | ||
| 107 | if ($this->parseFileConsole($file_path, $config)) { | 106 | if ($this->parseFileConsole($file_path, $config)) { |
| 108 | - unlink(\Yii::getAlias('@auto_upload') . '/' . $file_name . '.xml'); | 107 | + //unlink(\Yii::getAlias('@auto_upload') . '/' . $file_name . '.xml'); |
| 109 | \Yii::info("Загрузка файла - $file_path успешно завершена", 'parser'); | 108 | \Yii::info("Загрузка файла - $file_path успешно завершена", 'parser'); |
| 110 | } else { | 109 | } else { |
| 111 | \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser'); | 110 | \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser'); |
console/runtime/.gitignore
vendor/yiisoft/multiparser/CsvParser.php
| @@ -20,9 +20,6 @@ class CsvParser extends Parser | @@ -20,9 +20,6 @@ class CsvParser extends Parser | ||
| 20 | * если не указан и установлено свойство $hasHeaderRow - будет определен автоматически */ | 20 | * если не указан и установлено свойство $hasHeaderRow - будет определен автоматически */ |
| 21 | // public $keys; - определен в родительском классе | 21 | // public $keys; - определен в родительском классе |
| 22 | 22 | ||
| 23 | - /** @var экземляр SplFileObject читаемого файла */ | ||
| 24 | - public $file; | ||
| 25 | - | ||
| 26 | /** @var int - первая строка с которой начинать парсить */ | 23 | /** @var int - первая строка с которой начинать парсить */ |
| 27 | public $first_line = 0; | 24 | public $first_line = 0; |
| 28 | 25 |
vendor/yiisoft/multiparser/Parser.php
| @@ -18,6 +18,9 @@ abstract class Parser | @@ -18,6 +18,9 @@ abstract class Parser | ||
| 18 | public $keys = NULL; | 18 | public $keys = NULL; |
| 19 | public $hasHeaderRow = false; | 19 | public $hasHeaderRow = false; |
| 20 | 20 | ||
| 21 | + /** @var экземляр SplFileObject читаемого файла */ | ||
| 22 | + public $file; | ||
| 23 | + | ||
| 21 | public function setup() | 24 | public function setup() |
| 22 | { | 25 | { |
| 23 | $this->setupConverter(); | 26 | $this->setupConverter(); |
| 1 | +<?php | ||
| 2 | +/** | ||
| 3 | + * Created by PhpStorm. | ||
| 4 | + * User: Tsurkanov | ||
| 5 | + * Date: 21.10.2015 | ||
| 6 | + * Time: 15:44 | ||
| 7 | + */ | ||
| 8 | + | ||
| 9 | +namespace yii\multiparser; | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +use common\components\CustomVarDamp; | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +class XlsxParser extends Parser { | ||
| 16 | + public $path_for_extract_files = ''; | ||
| 17 | + | ||
| 18 | + public function setup() | ||
| 19 | + { | ||
| 20 | + parent::setup(); | ||
| 21 | + if ( $this->path_for_extract_files == '' ) { | ||
| 22 | + $this->path_for_extract_files = sys_get_temp_dir(); | ||
| 23 | + } | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + | ||
| 27 | + public function read() | ||
| 28 | + { | ||
| 29 | + //$this->extractFiles(); | ||
| 30 | + CustomVarDamp::dumpAndDie($this->parse()); | ||
| 31 | + | ||
| 32 | + // return $this->parse(); | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + protected function extractFiles () | ||
| 36 | + { | ||
| 37 | + $zip = new \ZipArchive; | ||
| 38 | + if ( $zip->open( $this->file->getPathname() ) === TRUE ) { | ||
| 39 | + $zip->extractTo( $this->path_for_extract_files ); | ||
| 40 | + $zip->close(); | ||
| 41 | + } else { | ||
| 42 | + throw new \Exception('Ошибка чтения xlsx файла'); | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + protected function parse () | ||
| 47 | + { | ||
| 48 | + $result = []; | ||
| 49 | + // while ($sheet = @readdir($this->file)) { | ||
| 50 | + foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) { | ||
| 51 | + //проходим по всем файлам из директории /xl/worksheets/ | ||
| 52 | + //CustomVarDamp::dumpAndDie($sheet); | ||
| 53 | + if ($sheet != "." && $sheet != ".." && $sheet != '_rels') { | ||
| 54 | + $xml = simplexml_load_file( $sheet ); | ||
| 55 | + //по каждой строке | ||
| 56 | + $row = 0; | ||
| 57 | + | ||
| 58 | + foreach ( $xml->sheetData->row as $item ) { | ||
| 59 | + $result[$sheet][$row] = array(); | ||
| 60 | + //по каждой ячейке строки | ||
| 61 | + $cell = 0; | ||
| 62 | + foreach ( $item as $child ) { | ||
| 63 | + // $attr = $child->attributes(); | ||
| 64 | + | ||
| 65 | + if( isset($child->v) ) { | ||
| 66 | + $value = (string)$child->v; | ||
| 67 | + }else{ | ||
| 68 | + $value = false; | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + // $result[$sheet][$row][$cell] = isset($attr['t']) ? $sharedStringsArr[$value] : $value; | ||
| 72 | + $result[$sheet][$row][$cell] = $value; | ||
| 73 | + $cell++; | ||
| 74 | + } | ||
| 75 | + $row++; | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | + return $result; | ||
| 80 | + } | ||
| 81 | +} | ||
| 0 | \ No newline at end of file | 82 | \ No newline at end of file |
vendor/yiisoft/multiparser/XmlParser.php
| @@ -13,8 +13,7 @@ use common\components\CustomVarDamp; | @@ -13,8 +13,7 @@ use common\components\CustomVarDamp; | ||
| 13 | use common\components\CustomArrayHelper; | 13 | use common\components\CustomArrayHelper; |
| 14 | 14 | ||
| 15 | class XmlParser extends Parser{ | 15 | class XmlParser extends Parser{ |
| 16 | - /** @var экземляр SplFileObject читаемого файла */ | ||
| 17 | - public $file; | 16 | + |
| 18 | public $node; | 17 | public $node; |
| 19 | 18 | ||
| 20 | public function read() | 19 | public function read() |
| @@ -86,7 +85,6 @@ class XmlParser extends Parser{ | @@ -86,7 +85,6 @@ class XmlParser extends Parser{ | ||
| 86 | // дошли до конца рекурсии | 85 | // дошли до конца рекурсии |
| 87 | // преобразуем ряд согласно конфигурации | 86 | // преобразуем ряд согласно конфигурации |
| 88 | if ( $this->keys !== NULL ) { | 87 | if ( $this->keys !== NULL ) { |
| 89 | - | ||
| 90 | // назначим ключи из конфигурации, согласно массиву $keys | 88 | // назначим ключи из конфигурации, согласно массиву $keys |
| 91 | $row = $this->compareArrayWithKeys( $row ); | 89 | $row = $this->compareArrayWithKeys( $row ); |
| 92 | } | 90 | } |