From a0d1ac8716ee35e76c563a45bc914d303476f189 Mon Sep 17 00:00:00 2001 From: Mihail Date: Tue, 13 Oct 2015 17:20:00 +0300 Subject: [PATCH] add articul filter into converter --- backend/controllers/ParserController.php | 5 ++++- backend/models/Details.php | 11 +++++++++-- common/components/parsers/CustomConverter.php | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------- common/components/parsers/CustomCsvParser.php | 2 +- common/components/parsers/config.php | 4 +++- console/controllers/ParserController.php | 3 +-- 6 files changed, 93 insertions(+), 34 deletions(-) diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index bd9e12f..09ef226 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -111,7 +111,10 @@ class ParserController extends BaseController // === ручная загрузка =========== //запускаем парсинг // доп. опции для парсера - $options = []; + $options = ['converter_conf' => + ['importer_id' => $files_model->importer_id] + ]; + if( ! $model->action ) // обработка с кастомным разделителем $options['$delimiter'] = $model->delimiter; diff --git a/backend/models/Details.php b/backend/models/Details.php index 1fa603c..4205cb9 100644 --- a/backend/models/Details.php +++ b/backend/models/Details.php @@ -130,14 +130,21 @@ class Details extends BaseActiveRecord $data = array_chunk($data, $this::BATCH); foreach ($data as $current_batch_array) { - //воспользуемся пакетной вставкой от фреймворка, плюс сразу с экранированием и защитой от инъекций + //воспользуемся пакетной вставкой от фреймворка $query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $current_batch_array)->sql; + if ($this->delete_prefix) { + $query_insert = $this->prepareArticul( $query_insert ); + } // добавим фрагмент с апдейтом при дубляже $query = "{$query_insert} {$query_update}"; // \common\components\CustomVarDamp::dumpAndDie($query); - $res = Yii::$app->db->createCommand($query)->execute(); + Yii::$app->db->createCommand($query)->execute(); } } + private function prepareArticul( $query_insert ){ + //CustomVarDamp::dumpAndDie($query_insert); + return $query_insert; + } } diff --git a/common/components/parsers/CustomConverter.php b/common/components/parsers/CustomConverter.php index 07f8718..8bb595d 100644 --- a/common/components/parsers/CustomConverter.php +++ b/common/components/parsers/CustomConverter.php @@ -1,10 +1,13 @@ $sub_value) { if (isset($key_array[$sub_key])) { // если такой ключ в базовом массиве (массиве ключей) есть, то заменим новым, иначе просто удалим $new_key = $key_array[$sub_key]; - if( !array_key_exists( $new_key , $res ) ){ - $res[ $new_key ] = $value[$sub_key]; + if (!array_key_exists($new_key, $res)) { + $res[$new_key] = $value[$sub_key]; } } - unset( $res[$sub_key] ); + unset($res[$sub_key]); $value = $res; } }, - $key_array); + $key_array); return $value_arr; } @@ -54,7 +62,7 @@ class CustomConverter extends Converter { * @param $add_array - массив с колонками (ключи) и значениями колонок * @return mixed */ - public function addColumns ( array $value_arr , array $add_array ) + public function addColumns(array $value_arr, array $add_array) { $i = 0; while ($i < count($value_arr)) { @@ -66,7 +74,7 @@ class CustomConverter extends Converter { return $value_arr; } - public static function convertToDetails ( array $row ) + public static function convertToDetails(array $row) { // присвоим полный артикул $row['FULL_ARTICLE'] = $row['ARTICLE']; @@ -75,19 +83,19 @@ class CustomConverter extends Converter { // проверим все ли обязательные колонки были указаны пользователем $details_model->load(['Details' => $row]); - if (!$details_model->validate()){ + if (!$details_model->validate()) { $errors = ''; - foreach ( $details_model->errors as $key => $arr_errors ) { - $errors .= "Аттрибут $key - " . implode( ' , ', $arr_errors ); + foreach ($details_model->errors as $key => $arr_errors) { + $errors .= "Аттрибут $key - " . implode(' , ', $arr_errors); } - throw new \ErrorException( $errors ); + throw new \ErrorException($errors); } return $row; } - public function ConvertToMultiply ( array $row ) + public function ConvertToMultiply(array $row) { - $PRICE = $row[ 'PRICE' ]; + $PRICE = $row['PRICE']; $sign = self::$sign; $multiplier = self::$multiplier; //CustomVarDamp::dumpAndDie(self); @@ -96,28 +104,68 @@ class CustomConverter extends Converter { if ($multiplier > 0) { $PRICE += $multiplier; } - } - else if ($sign == '-') { + } else if ($sign == '-') { if ($multiplier > 0) { $PRICE -= $multiplier; } - } - else if ($sign == '*') { + } else if ($sign == '*') { if ($multiplier > 0) { $PRICE *= $multiplier; } - } - else if ($sign == '/') { + } else if ($sign == '/') { if ($multiplier > 0) { $PRICE /= $multiplier; } } } - $row[ 'PRICE' ] = $PRICE; + $row['PRICE'] = $PRICE; + + return $row; + + } + + public static function convertToArticul(array $row) + { + if (isset($row['ARTICLE']) && isset($row['BRAND']) && isset(self::$importer_id)) { + + // 1. Уберем префикс который разделен пробелом (если он есть) + $words = explode(" ", $row['ARTICLE']); + if (count($words) > 1) { + array_shift($words); + $row['ARTICLE'] = implode(" ", $words); + } + + // 2. Уберем брендовый префикс (если он есть) + $prefix = ''; + // запрос закешируем + $prefix = ImportersPrefix::getDb()->cache( function ($db, $configuration, $row ) { + return ImportersPrefix::find()->where([ 'importer_id' => self::$importer_id, + 'brand' => $row['BRAND'] ])->one(); + }); + if ($prefix) { + $row['BRAND'] = str_replace($prefix, "", $row['BRAND']); + } + } return $row; + } + + public static function convertToBrand($value) + { + $res = $value; + $res = trim(strtoupper($res)); + $res = str_replace("Ä", "A", str_replace("Ö", "O", str_replace("Ü", "U", str_replace("Ë", "E", str_replace("Ò", "O", $res))))); + $res = str_replace(array('@', '#', '~', '"', "'", "?", "!"), '', $res); + + return $res; + } + + public static function convertToString($value) + { + $value = parent::convertToString($value); + return str_replace(array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '~', '`', '"', "'", ' ', '№', '%', ';', ':', '[', ']', '{', '}', '*', '?', '/', '\'', '|', '.', ',', '<', '>', '\\'), '', $value); } diff --git a/common/components/parsers/CustomCsvParser.php b/common/components/parsers/CustomCsvParser.php index 6a7caf6..ed92588 100644 --- a/common/components/parsers/CustomCsvParser.php +++ b/common/components/parsers/CustomCsvParser.php @@ -16,7 +16,7 @@ use yii\base\ErrorException; class CustomCsvParser extends \yii\multiparser\CsvParser { - public $last_line = 10; + public $last_line = 100; //public $hasHeaderRow = true; // public $keys = ['first','second', 'third', 'forth', 'fifth']; public function setupConverter() diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index 4a423cb..98e7389 100644 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -17,9 +17,11 @@ 'hasKey' => 1, 'configuration' => ["string" => 'DESCR', "float" => 'PRICE', + "brand" => 'BRAND', "integer" => ['BOX','ADD_BOX'], "multiply" => [], - "details" => [] // @todo сделать отдельно конфигурирование валидации + "details" => [], + "articul" => [] ] ],], diff --git a/console/controllers/ParserController.php b/console/controllers/ParserController.php index aa725c8..cd04973 100644 --- a/console/controllers/ParserController.php +++ b/console/controllers/ParserController.php @@ -32,8 +32,7 @@ class ParserController extends Controller 'importer_id' => $importer_id, 'parser_config' => ['keys' => $keys, 'converter_conf' => - ['sign' => $sign, - 'multiplier' => $multiplier], + [ 'sign' => $sign, 'multiplier' => $multiplier, 'importer_id' => $importer_id ], 'mode' => 'console'] ]; if ($this->parseFileConsole($file_path, $config)) { -- libgit2 0.21.4