diff --git a/backend/components/parsers/CustomCsvParser.php b/backend/components/parsers/CustomCsvParser.php index dd28725..938a1ed 100644 --- a/backend/components/parsers/CustomCsvParser.php +++ b/backend/components/parsers/CustomCsvParser.php @@ -9,6 +9,8 @@ namespace backend\components\parsers; +use common\components\CustomVarDamp; + class CustomCsvParser extends \yii\multiparser\CsvParser { public $last_line = 10; @@ -33,9 +35,8 @@ class CustomCsvParser extends \yii\multiparser\CsvParser { */ protected function convert($arr) { - $result = \Yii::$app->multiparser->convertByConfiguration( $arr, $this->converter_conf ); - - return $result; + $arr = \Yii::$app->multiparser->convertByConfiguration($arr, $this->converter_conf); + return $arr; } diff --git a/backend/components/parsers/config.php b/backend/components/parsers/config.php index 3db7f86..6731f4b 100644 --- a/backend/components/parsers/config.php +++ b/backend/components/parsers/config.php @@ -21,7 +21,9 @@ 'console' => ['class' => 'backend\components\parsers\CustomCsvParser', 'auto_detect_first_line' => true, + 'hasHeaderRow' => true, 'converter_conf' => ['class' => ' backend\components\parsers\CustomConverter', + 'hasKey' => 1, 'configuration' => ["string" => 'DESCR', "float" => 'PRICE', "integer" => ['BOX','ADD_BOX'] diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 4a0271f..e995fc6 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -16,7 +16,6 @@ use backend\models\Importers; use yii\base\ErrorException; use common\components\PriceWriter; use common\components\CustomVarDamp; -use yii\web\ErrorAction; /** * Parser controller @@ -225,7 +224,7 @@ class ParserController extends BaseController $file_id = basename($server_file,".csv"); $arr_id_files[] = (int) $file_id; } - Yii::$app->cache->set( 'files_to_delete',json_encode( $arr_id_files ) ); + Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) ); $query = ImportersFiles::find()->where(['in', 'id', $arr_id_files])->orderBy(['upload_time' => SORT_DESC]); $provider = new ActiveDataProvider([ @@ -251,23 +250,79 @@ class ParserController extends BaseController unlink(Yii::getAlias('@auto_upload') . '/' . $id . '.csv' ); // удалим этот id и из кэша - if( $arr_id_files = Yii::$app->cache->get( 'files_to_delete' ) ){ + if( $arr_id_files = Yii::$app->cache->get( 'files_to_parse' ) ){ $arr_id_files = json_decode($arr_id_files); if (isset( $arr_id_files[$id] ) ) { unset( $arr_id_files[$id] ); // положем уже обновленный массив - Yii::$app->cache->set( 'files_to_delete',json_encode( $arr_id_files ) ); + Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) ); } } // сообщим скрипту что все ОК echo 1; } catch (ErrorException $e) { - CustomVarDamp::dump($e->getMessage()); + //CustomVarDamp::dump($e->getMessage()); + throw $e; } } } } + + + + + public function actionParse () + { +// $comand = "/usr/bin/php -f ".Yii::getAlias('@console') ."/Controllers/ParserController.php"; +// exec($comand); + if( $arr_id_files = Yii::$app->cache->get( 'files_to_parse' ) ) { + $arr_id_files = json_decode( $arr_id_files ); + foreach ( $arr_id_files as $file_name ) { + $file_path = Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv'; + $config = ['record_id' => $file_name, + 'importer_id' => ImportersFiles::findOne(['id' => $file_name])->id, + 'parser_config' => ['keys' => ['DESCR', 'ARTICLE', 'BRAND', 'PRICE', 'BOX'], + 'mode' => 'console'] + ]; + if( $this->parseFileConsole( $file_path, $config ) ){ + unlink( $file_path ); + if (isset( $arr_id_files[$file_path] ) ) { + unset($arr_id_files[$file_path]); + } + } else { + // Yii::$app->log-> + // не дошли до конца по этому остаки вернем в кеш + Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) ); + } + } + if ( !count( $arr_id_files ) ) { + Yii::$app->cache->delete( 'files_to_parse' ); + } + } + + return $this->redirect('serverFiles'); + } + + protected function parseFileConsole( $file_path, $configuration ){ + $parser_config = []; + if ( isset( $configuration['parser_config'] ) ) { + $parser_config = $configuration['parser_config']; + } + + $data = Yii::$app->multiparser->parse( $file_path, $parser_config ); + CustomVarDamp::dumpAndDie($data); + $writer = new PriceWriter(); + $writer->configuration = $configuration; + $writer->data = $data; + $writer->mode = 1; //console-режим + if ( $writer->writeDataToDB() ){ + //Console::output('It is working'); + return true; + } + + return false; + } } diff --git a/backend/views/parser/server-files.php b/backend/views/parser/server-files.php index 2bc638a..cd7160b 100644 --- a/backend/views/parser/server-files.php +++ b/backend/views/parser/server-files.php @@ -1,5 +1,6 @@ 'server_files_grid']); ]] );?> - + 'btn btn-success']) ?> configuration->record_id ); + $files_model = ImportersFiles::findOne( $this->configuration['record_id'] ); //$files_model->load(['ImportersFiles' => $this->configuration->toArray()]); $update_date = date('Y-m-d H:i:s'); @@ -61,7 +61,7 @@ class PriceWriter { } else{ // дополним данные значением импортера и даты обновления цены - $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration->importer_id, 'timestamp' => $update_date]); + $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]); try { //@todo add transaction diff --git a/console/controllers/ParserController.php b/console/controllers/ParserController.php index a600e17..109a588 100644 --- a/console/controllers/ParserController.php +++ b/console/controllers/ParserController.php @@ -6,19 +6,59 @@ * Time: 14:38 */ use yii\console\Controller; +use yii\helpers\Console; +use common\components\PriceWriter; +use backend\models\ImportersFiles; class ParserController extends Controller{ public function actionParseCSV () { - + \common\components\CustomVarDamp::dumpAndDie(45); + if( $arr_id_files = Yii::$app->cache->get( 'files_to_parse' ) ) { + $arr_id_files = json_decode( $arr_id_files ); + foreach ( $arr_id_files as $file_name ) { + $file_path = Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv'; + $config = ['record_id' => $file_name, + 'importer_id' => ImportersFiles::findOne(['id' => $file_name])->id, + 'parser_config' => ['keys' => ['DESCR', 'ARTICLE', 'BRAND', 'PRICE', 'BOX']] + ]; + if( $this->parseFileConsole( $file_path, $config ) ){ + unlink( $file_path ); + if (isset( $arr_id_files[$file_path] ) ) { + unset($arr_id_files[$file_path]); + } + } else { + // Yii::$app->log-> + // не дошли до конца по этому остаки вернем в кеш + Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) ); + } + } + if ( !count( $arr_id_files ) ) { + Yii::$app->cache->delete( 'files_to_parse' ); + } + } } public function actionParseXML () { } - protected function parseFileConsole( $file_path ){ + protected function parseFileConsole( $file_path, $configuration ){ + $parser_config = []; + if ( isset( $configuration['parser_config'] ) ) { + $parser_config = $configuration['parser_config']; + } + + $data = Yii::$app->multiparser->parse( $file_path, $parser_config ); - $data = Yii::$app->multiparser->parse( $file_path ); + $writer = new PriceWriter(); + $writer->configuration = $configuration; + $writer->data = $data; + $writer->mode = 1; //console-режим + if ( $writer->writeDataToDB() ){ + Console::output('It is working'); + return true; + } + return false; } } \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/Converter.php b/vendor/yiisoft/multiparser/Converter.php index eda4887..5c38942 100644 --- a/vendor/yiisoft/multiparser/Converter.php +++ b/vendor/yiisoft/multiparser/Converter.php @@ -7,6 +7,7 @@ */ namespace yii\multiparser; +use common\components\CustomVarDamp; use yii\base\Behavior; // класс который содержит преобразователи значений (фильтры) используемые при парсинге @@ -19,7 +20,6 @@ class Converter extends Behavior public static function convertToFloat($value) { - echo 1; if ($value == '') { $value = 0; } @@ -51,8 +51,6 @@ class Converter extends Behavior public static function convertToString($value) { - - $res = ''; if (is_array($value)) { @@ -101,7 +99,7 @@ class Converter extends Behavior public static function convertByConfiguration( $arr, $configuration ) { $result = $arr; - //\common\components\CustomVarDamp::dumpAndDie($configuration); + // \common\components\CustomVarDamp::dumpAndDie( $result ); $hasKey = isset( $configuration['hasKey'] ); foreach ( $configuration['configuration'] as $key => $value ) { @@ -111,7 +109,7 @@ class Converter extends Behavior foreach ($value as $sub_value) { if (isset($arr[$sub_value])) { // конвертируем только те ячейки которые сопоставлены в прочитанном массиве с колонками в конфигурационном файле - $result[$arr[$sub_value]] = self::$key( $arr[$sub_value] ); + $result[$sub_value] = self::$key( $arr[$sub_value] ); } } @@ -119,7 +117,7 @@ class Converter extends Behavior if (isset($arr[$value])) { // конвертируем только те ячейки которые сопоставлены в прочитанном массиве с колонками в конфигурационном файле - $result[$arr[$value]] = self::$key( $arr[$value] ); + $result[$value] = self::$key( $arr[$value] ); } } diff --git a/vendor/yiisoft/multiparser/CsvParser.php b/vendor/yiisoft/multiparser/CsvParser.php index fee2fc5..8d37637 100644 --- a/vendor/yiisoft/multiparser/CsvParser.php +++ b/vendor/yiisoft/multiparser/CsvParser.php @@ -3,6 +3,7 @@ */ namespace yii\multiparser; +use common\components\CustomVarDamp; /** @@ -97,7 +98,7 @@ class CsvParser implements ParserInterface while (!$finish) { $j = 0; - $row = $this->readRow(); + $row = $this->file->fgetcsv();; if ($row === false) { continue; } @@ -129,7 +130,7 @@ class CsvParser implements ParserInterface $empty_lines = 0; while ( $empty_lines < 3 ) { // прочтем строку из файла. Если там есть значения - то в ней массив, иначе - false - $row = $this->readRow(); + $row = $this->readRow( $current_line ); if ($row === false) { //счетчик пустых строк @@ -139,19 +140,10 @@ class CsvParser implements ParserInterface // строка не пустая, имеем прочитанный массив значений $current_line++; if ($this->hasHeaderRow) { + // в файле есть заголовок, но он еще не назначен, назначим if ($this->keys === NULL) { $this->keys = array_values($row); - } else { - - if (count($this->keys) !== count($row)) { -// - throw new \ErrorException("Invalid columns detected on line # {$current_line}", 0, 1, $this->file->getBasename(), $current_line); - } - - $return[] = array_combine($this->keys, $row); } - } else { - $return[] = $row; } // если у нас установлен лимит, при его достижении прекращаем парсинг if (($this->last_line) && ($current_line > $this->last_line)) { @@ -159,6 +151,8 @@ class CsvParser implements ParserInterface } // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД $empty_lines = 0; + + $return[] = $row; } $this->closeHandler(); @@ -174,16 +168,24 @@ class CsvParser implements ParserInterface /** * @return array - одномерный массив результата парсинга строки */ - protected function readRow() + protected function readRow( $current_line ) { - $row = $this->file->fgetcsv(); - if (is_array($row)) { - // попытаемся конвертировать прочитанные занчения согдасно конфигурации котнвертера значений + // если есть заголовок, то перед конвертацией его нужно назначить + if ($this->hasHeaderRow && $this->keys !== NULL) { + + if (count($this->keys) !== count($row)) { +// + throw new \ErrorException("Ошибка парсинга файла в строке # {$current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $current_line); + } + + $row = array_combine($this->keys, $row); + } + // попытаемся конвертировать прочитанные значения согласно конфигурации котнвертера значений $row = $this->convert($row); - // \common\components\CustomVarDamp::dump($row); - if ($this->first_column) { + // обрежем массив к первой значимой колонке + if ( $this->first_column ) { $row = array_slice($row, $this->first_column); diff --git a/vendor/yiisoft/multiparser/YiiMultiparser.php b/vendor/yiisoft/multiparser/YiiMultiparser.php index eab9962..58ff2d7 100644 --- a/vendor/yiisoft/multiparser/YiiMultiparser.php +++ b/vendor/yiisoft/multiparser/YiiMultiparser.php @@ -39,14 +39,5 @@ public $configuration; } - public function init() - { - if( isset($this->configuration['glob']) && isset($this->configuration['glob']['ini'])){ - foreach ($this->configuration['glob']['ini'] as $ini_setting => $ini_setting_value) { - ini_set( $ini_setting, $ini_setting_value ); - } - } - - } } \ No newline at end of file -- libgit2 0.21.4