diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index afabb24..f838024 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -266,13 +266,15 @@ class ParserController extends BaseController foreach (glob(Yii::getAlias('@temp_upload') . '/*.csv') as $server_file) { $file_name = basename($server_file,".csv"); - // rename( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv'); copy( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv' ); } + Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' ); $this->redirect('server-files'); +// $csv = new \console\controllers\ParserController( 'parse-csv', $this->module ); +// $csv->actionParseCsv(); } diff --git a/backend/models/Importers.php b/backend/models/Importers.php index d6f7d2d..221b09e 100644 --- a/backend/models/Importers.php +++ b/backend/models/Importers.php @@ -2,6 +2,7 @@ namespace backend\models; +use common\components\CustomVarDamp; use Yii; use backend\components\base\BaseActiveRecord; @@ -93,6 +94,7 @@ class Importers extends BaseActiveRecord { // возьмем только поля описанные в fields() - там как раз наши настройки парсера $arr = $this->toArray(); + // отсортируем по ключам с учетом преобразования в число asort($arr, SORT_NUMERIC); // уберем нулевые колонки @@ -101,10 +103,21 @@ class Importers extends BaseActiveRecord }); // нам нужны именно ключи $arr = array_keys($arr); + return $arr; + } + + + public function getMultiply () + { + $arr['sign'] = $this->PARSER_FIELD_SIGN; + $arr['multiplier'] = $this->PARSER_FIELD_MULTIPLIER; + return $arr; } + + public function fields() { return [ @@ -119,5 +132,4 @@ class Importers extends BaseActiveRecord } - } diff --git a/common/components/parsers/CustomConverter.php b/common/components/parsers/CustomConverter.php index 4b2a084..07f8718 100644 --- a/common/components/parsers/CustomConverter.php +++ b/common/components/parsers/CustomConverter.php @@ -11,6 +11,9 @@ class CustomConverter extends Converter { * @param $key_array - ключи для вложенного массива * @return array - таблица с проименованными колонками */ + public static $sign; + public static $multiplier; + public static function convertToAssocArray ( array $value_arr, array $key_array, $key_prefix = '' ) { // очистка служебного префикса в массиве заголовков @@ -82,6 +85,40 @@ class CustomConverter extends Converter { return $row; } + public function ConvertToMultiply ( array $row ) + { + $PRICE = $row[ 'PRICE' ]; + $sign = self::$sign; + $multiplier = self::$multiplier; + //CustomVarDamp::dumpAndDie(self); + if (isset($sign)) { + if ($sign == '+') { + if ($multiplier > 0) { + $PRICE += $multiplier; + } + } + else if ($sign == '-') { + if ($multiplier > 0) { + $PRICE -= $multiplier; + } + } + else if ($sign == '*') { + if ($multiplier > 0) { + $PRICE *= $multiplier; + } + } + else if ($sign == '/') { + if ($multiplier > 0) { + $PRICE /= $multiplier; + } + } + } + + $row[ 'PRICE' ] = $PRICE; + + return $row; + + } } \ No newline at end of file diff --git a/common/components/parsers/CustomCsvParser.php b/common/components/parsers/CustomCsvParser.php index 72af4e7..6a7caf6 100644 --- a/common/components/parsers/CustomCsvParser.php +++ b/common/components/parsers/CustomCsvParser.php @@ -25,10 +25,12 @@ class CustomCsvParser extends \yii\multiparser\CsvParser { if ($this->hasHeaderRow) { // если у файла есть заголовок, то в результате имеем ассоциативный массив $this->converter_conf['hasKey'] = 1; + } } - +// $this->converter = \Yii::createObject( $this->converter_conf ); +// CustomVarDamp::dumpAndDie($this->converter); } /** @@ -38,7 +40,7 @@ class CustomCsvParser extends \yii\multiparser\CsvParser { */ protected function convert($arr) { - $arr = \Yii::$app->multiparser->convertByConfiguration($arr, $this->converter_conf); + $arr = \Yii::$app->multiparser->convertByConfiguration( $arr, $this->converter_conf ); return $arr; diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index 1908466..4a423cb 100644 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -4,18 +4,21 @@ ['web' => ['class' => 'common\components\parsers\CustomCsvParser', 'auto_detect_first_line' => true, - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter', + 'converter_conf' => [ + //'class' => ' common\components\parsers\CustomConverter', // @todo переделать на подключаемый behavior 'configuration' => ["string" => 'DESCR'],] ], 'console' => ['class' => 'common\components\parsers\CustomCsvParser', 'auto_detect_first_line' => true, 'hasHeaderRow' => true, - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter', + 'converter_conf' => [ + //'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => ["string" => 'DESCR', "float" => 'PRICE', "integer" => ['BOX','ADD_BOX'], + "multiply" => [], "details" => [] // @todo сделать отдельно конфигурирование валидации ] @@ -36,7 +39,8 @@ ['console' => ['class' => 'yii\multiparser\XmlParser', 'node' => 'Товар', - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter', + 'converter_conf' => [ + //'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => ["details" => [] ],], diff --git a/console/controllers/ParserController.php b/console/controllers/ParserController.php index 3d210ec..aa725c8 100644 --- a/console/controllers/ParserController.php +++ b/console/controllers/ParserController.php @@ -1,6 +1,7 @@ $file_name])->importer_id; - $keys = Importers::findOne(['id' => $importer_id])->keys; + $current_importer = Importers::findOne(['id' => $importer_id]); + $keys = $current_importer->keys; + $mult_array = $current_importer->multiply; + + // получим настройки ценообразования и передадим их отдельно в конвертер + $sign = ''; + $multiplier = ''; + extract( $mult_array ); + $config = ['record_id' => $file_name, 'importer_id' => $importer_id, 'parser_config' => ['keys' => $keys, + 'converter_conf' => + ['sign' => $sign, + 'multiplier' => $multiplier], 'mode' => 'console'] ]; if ($this->parseFileConsole($file_path, $config)) { @@ -48,7 +59,7 @@ class ParserController extends Controller $parser_config = $configuration['parser_config']; } $data = \Yii::$app->multiparser->parse( $file_path, $parser_config ); - if (! $data) { + if ( ! $data ) { // @todo переделать, что бы ошибка автоматически останавливала сценарий return false; } diff --git a/vendor/yiisoft/multiparser/Converter.php b/vendor/yiisoft/multiparser/Converter.php index e5d8524..c6065c3 100644 --- a/vendor/yiisoft/multiparser/Converter.php +++ b/vendor/yiisoft/multiparser/Converter.php @@ -9,6 +9,7 @@ namespace yii\multiparser; use common\components\CustomVarDamp; use yii\base\Behavior; +use yii\base\ErrorException; // класс который содержит преобразователи значений (фильтры) используемые при парсинге class Converter extends Behavior @@ -98,8 +99,23 @@ class Converter extends Behavior */ public static function convertByConfiguration( $arr, $configuration ) { - $hasKey = isset( $configuration['hasKey'] ); - foreach ( $configuration['configuration'] as $key => $value ) { + if( $hasKey = isset( $configuration['hasKey'] ) ) + unset( $configuration['hasKey'] ); + + if ( isset( $configuration['configuration'] ) ) { + $arr_config = $configuration['configuration']; + unset( $configuration['configuration'] ); + } else{ + throw new ErrorException('Не указан обязательный параметр конфигурационного файла - converter_conf[configuration]'); + } + + // проставим аттрибуды из конфига{}{} + foreach ($configuration as $key_setting => $setting) { + if( property_exists( static::class, $key_setting ) ) + static::$$key_setting = $setting; + } + + foreach ( $arr_config as $key => $value ) { if ( $hasKey ){ // у нас ассоциативный массив, и мы можем конвертировать каждое значение в отдельности if ( is_array( $value ) ) { diff --git a/vendor/yiisoft/multiparser/CsvParser.php b/vendor/yiisoft/multiparser/CsvParser.php index 8d37637..b64ef8e 100644 --- a/vendor/yiisoft/multiparser/CsvParser.php +++ b/vendor/yiisoft/multiparser/CsvParser.php @@ -50,6 +50,8 @@ class CsvParser implements ParserInterface public $converter_conf = []; /** @var array - конвертер созданный по конфигурации */ public $converter = NULL; + /** @var int - текущая строка */ + private $current_line = 0; /** @@ -95,8 +97,9 @@ class CsvParser implements ParserInterface { $finish = false; - while (!$finish) { + $this->current_line ++; + $j = 0; $row = $this->file->fgetcsv();; if ($row === false) { @@ -104,6 +107,7 @@ class CsvParser implements ParserInterface } for ($i = 1; $i <= count($row); $i++) { + // CustomVarDamp::dump($row[$i]); if ($row[$i - 1] <> '') { $j++; @@ -114,6 +118,9 @@ class CsvParser implements ParserInterface } } } + die(); + // $this->current_line --; + $this->file->seek( $this->current_line ); } /** @@ -125,12 +132,11 @@ class CsvParser implements ParserInterface $return = []; - $current_line = 0; // будем считать количество пустых строк подряд - при трех подряд - считаем что это конец файла и выходим $empty_lines = 0; while ( $empty_lines < 3 ) { // прочтем строку из файла. Если там есть значения - то в ней массив, иначе - false - $row = $this->readRow( $current_line ); + $row = $this->readRow( ); if ($row === false) { //счетчик пустых строк @@ -138,7 +144,7 @@ class CsvParser implements ParserInterface continue; } // строка не пустая, имеем прочитанный массив значений - $current_line++; + $this->current_line++; if ($this->hasHeaderRow) { // в файле есть заголовок, но он еще не назначен, назначим if ($this->keys === NULL) { @@ -146,7 +152,7 @@ class CsvParser implements ParserInterface } } // если у нас установлен лимит, при его достижении прекращаем парсинг - if (($this->last_line) && ($current_line > $this->last_line)) { + if (($this->last_line) && ($this->current_line > $this->last_line)) { break; } // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД @@ -168,16 +174,19 @@ class CsvParser implements ParserInterface /** * @return array - одномерный массив результата парсинга строки */ - protected function readRow( $current_line ) + protected function readRow( ) { $row = $this->file->fgetcsv(); + // уберем нулевые колонки + $row = array_filter($row, function($val){ + return $val <> ''; + }); 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); + throw new \ErrorException("Ошибка парсинга файла в строке # {$this->current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_line); } $row = array_combine($this->keys, $row); diff --git a/vendor/yiisoft/multiparser/YiiParserHandler.php b/vendor/yiisoft/multiparser/YiiParserHandler.php index eb3cb4f..5bf86ad 100644 --- a/vendor/yiisoft/multiparser/YiiParserHandler.php +++ b/vendor/yiisoft/multiparser/YiiParserHandler.php @@ -9,6 +9,8 @@ namespace yii\multiparser; +use common\components\CustomVarDamp; + class YiiParserHandler extends ParserHandler{ @@ -46,8 +48,7 @@ class YiiParserHandler extends ParserHandler{ try { $this->configuration = \Yii::$app->multiparser->getConfiguration($this->extension, $this->mode); - $this->configuration = array_merge($this->configuration, $options); - + $this->configuration = array_merge_recursive ($this->configuration, $options); } catch (\ErrorException $e) { echo $e->getMessage(); return []; -- libgit2 0.21.4