From 67adc7885f3d5afe0b8340909d5bf0cdd18affea Mon Sep 17 00:00:00 2001 From: Mihail Date: Tue, 20 Oct 2015 17:56:09 +0300 Subject: [PATCH] add converter interface, object creator, abstract class Parser --- backend/controllers/ParserController.php | 4 ++-- backend/models/UploadFileParsingForm.php | 4 ++-- common/components/CustomArrayHelper.php | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ common/components/PriceWriter.php | 12 ++++++------ common/components/parsers/CustomConverter.php | 74 ++------------------------------------------------------------------------ common/components/parsers/CustomCsvParser.php | 40 ++++++++++++++-------------------------- common/components/parsers/config.php | 8 ++++---- common/config/main.php | 11 ++++++----- common/models/DetailsCurrency.php | 2 +- 9 files changed, 112 insertions(+), 118 deletions(-) create mode 100644 common/components/CustomArrayHelper.php diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index cfcce21..7854d4f 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -15,6 +15,7 @@ use backend\models\Importers; use yii\base\ErrorException; use common\components\PriceWriter; use common\components\CustomVarDamp; +use common\components\CustomArrayHelper; /** * Parser controller @@ -54,7 +55,6 @@ class ParserController extends BaseController $model = new UploadFileParsingForm(); // установим режим, 0 - ручная загрузка, 1 - автозагрузка $model->mode = $mode; - //CustomVarDamp::dumpAndDie(phpinfo()); return $this->render('index', ['model' => $model]); } @@ -186,7 +186,7 @@ class ParserController extends BaseController // соотнесем отпарсенные данные с соответсивем полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию - $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr , 'attr_'); + $data = CustomArrayHelper::createAssocArray( $data, $arr , 'attr_' ); // запустим специальный класс который запишет данные в таблицы связанные с прайсами $writer = new PriceWriter(); diff --git a/backend/models/UploadFileParsingForm.php b/backend/models/UploadFileParsingForm.php index c66ab5e..165d7a1 100644 --- a/backend/models/UploadFileParsingForm.php +++ b/backend/models/UploadFileParsingForm.php @@ -75,8 +75,8 @@ class UploadFileParsingForm extends Model throw new ErrorException("Ошибка чтения из файла прайса {$this->file_path}"); } // файл больше не нужен - данные прочитаны и сохранены в кеш - if( file_exists($this->file_path) ) - unlink($this->file_path); +// if( file_exists($this->file_path) ) +// unlink($this->file_path); return $data; } diff --git a/common/components/CustomArrayHelper.php b/common/components/CustomArrayHelper.php new file mode 100644 index 0000000..bd76aa6 --- /dev/null +++ b/common/components/CustomArrayHelper.php @@ -0,0 +1,75 @@ + $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]; + } + } + unset($res[$sub_key]); + $value = $res; + } + + }, + $key_array); + + return $value_arr; + } + + /** + * @param $value_arr - двумерный массив к которому нужно добавить колонки + * @param $add_array - массив с колонками (ключи) и значениями колонок + * @return mixed + */ + public static function addColumns(array $value_arr, array $add_array) + { + $i = 0; + while ($i < count($value_arr)) { + foreach ($add_array as $add_key => $add_value) { + $value_arr[$i][$add_key] = $add_value; + } + $i++; + } + return $value_arr; + } +} \ No newline at end of file diff --git a/common/components/PriceWriter.php b/common/components/PriceWriter.php index ecc88ff..d6b27a5 100644 --- a/common/components/PriceWriter.php +++ b/common/components/PriceWriter.php @@ -62,20 +62,20 @@ class PriceWriter // преобразуем числовые значения foreach ($this->data as &$row) { - $row['PRICE'] = \Yii::$app->multiparser->convertToFloat($row['PRICE']); - $row['BOX'] = \Yii::$app->multiparser->convertToInteger($row['BOX']); + $row['PRICE'] = \Yii::$app->converter->convertTo('float',$row['PRICE']); + $row['BOX'] = \Yii::$app->converter->convertTo('integer',$row['BOX']); // присвоим полный артикул $row['FULL_ARTICLE'] = $row['ARTICLE']; if ((int)$this->configuration['delete_prefix']) { - $row = \Yii::$app->multiparser->convertToArticle( $row, $this->configuration['importer_id'] ); + $row = \Yii::$app->converter->convertTo( 'Article', $row, ['importer_id' => $this->configuration['importer_id']] ); } else { - $row['ARTICLE'] = \Yii::$app->multiparser->convertToArticle( $row['ARTICLE'] ); + $row['ARTICLE'] = \Yii::$app->converter->convertTo( 'Article', $row['ARTICLE'] ); } if (isset($row['ADD_BOX'])) - $row['ADD_BOX'] = \Yii::$app->multiparser->convertToInteger($row['ADD_BOX']); + $row['ADD_BOX'] = \Yii::$app->converter->convertTo( 'integer', $row['ADD_BOX'] ); // проверим все ли обязательные колонки были указаны пользователем $details_model->load(['Details' => $row]); @@ -87,7 +87,7 @@ class PriceWriter } // дополним данные значением импортера и даты обновления цены - $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]); + $this->data = CustomArrayHelper::addColumns( $this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date] ); try { //@todo add transaction diff --git a/common/components/parsers/CustomConverter.php b/common/components/parsers/CustomConverter.php index e233f87..7907fe1 100644 --- a/common/components/parsers/CustomConverter.php +++ b/common/components/parsers/CustomConverter.php @@ -10,71 +10,11 @@ use backend\models\ImportersPrefix; class CustomConverter extends Converter { - /** - * @param $value_arr - двумерный массив значений, которому нужно присвоить ключи - * @param $key_array - ключи для вложенного массива - * @return array - таблица с проименованными колонками - */ public static $sign; public static $multiplier; public static $importer_id; public static $brand; - public static function convertToAssocArray(array $value_arr, array $key_array, $key_prefix = '') - { - // очистка служебного префикса в массиве заголовков - if ($key_prefix) { - // @todo оптимизировать - два переворота массива - избыточно - $key_array = array_flip($key_array); - - array_walk($key_array, function (&$value, $key, $key_prefix) { - $value = str_replace($key_prefix, '', $value); - }, $key_prefix); - - $key_array = array_flip($key_array); - //уберем пустые элементы - $key_array = array_filter($key_array, function ($value) { - return $value !== ''; - }); - } - - array_walk($value_arr, - function (&$value, $key, $key_array) { - $res = $value; - foreach ($res as $sub_key => $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]; - } - } - unset($res[$sub_key]); - $value = $res; - } - - }, - $key_array); - - return $value_arr; - } - - /** - * @param $value_arr - двумерный массив к которому нужно добавить колонки - * @param $add_array - массив с колонками (ключи) и значениями колонок - * @return mixed - */ - public function addColumns(array $value_arr, array $add_array) - { - $i = 0; - while ($i < count($value_arr)) { - foreach ($add_array as $add_key => $add_value) { - $value_arr[$i][$add_key] = $add_value; - } - $i++; - } - return $value_arr; - } public static function convertToDetails(array $row) { @@ -143,11 +83,8 @@ class CustomConverter extends Converter } - public static function convertToArticle( $value, $importer_id = '' ) + public static function convertToArticle( $value ) { - if(isset( $importer_id )){ - self::$importer_id = $importer_id; - } if (is_array($value)) { @@ -189,7 +126,7 @@ class CustomConverter extends Converter public static function convertToBrand($value) { - $res = parent::convertToEncode($value);; + $res = self::convertToEncode($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); @@ -197,12 +134,5 @@ class CustomConverter extends Converter return $res; } - public static function convertToString($value) - { - $value = parent::convertToEncode($value); - - return str_replace(array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '~', '`', '"', "'", ' ', '№', '%', ';', ':', '[', ']', '{', '}', '*', '?', '/', '\'', '|', '.', ',', '<', '>', '\\'), '', $value); - } - } \ No newline at end of file diff --git a/common/components/parsers/CustomCsvParser.php b/common/components/parsers/CustomCsvParser.php index ed92588..b21fbca 100644 --- a/common/components/parsers/CustomCsvParser.php +++ b/common/components/parsers/CustomCsvParser.php @@ -19,31 +19,19 @@ class CustomCsvParser extends \yii\multiparser\CsvParser { public $last_line = 100; //public $hasHeaderRow = true; // public $keys = ['first','second', 'third', 'forth', 'fifth']; - public function setupConverter() - { - if (!count($this->converter_conf)) { - if ($this->hasHeaderRow) { - // если у файла есть заголовок, то в результате имеем ассоциативный массив - $this->converter_conf['hasKey'] = 1; - - } - - } -// $this->converter = \Yii::createObject( $this->converter_conf ); -// CustomVarDamp::dumpAndDie($this->converter); - } - - /** - * @param $arr - * @return mixed - * преобразовует значения прочитанного массива в нужные типы, согласно конфигурации конвертера - */ - protected function convert($arr) - { - $arr = \Yii::$app->multiparser->convertByConfiguration( $arr, $this->converter_conf ); - - return $arr; - - } +// public function setupConverter() +// { +// if (!count($this->converter_conf)) { +// if ($this->hasHeaderRow) { +// // если у файла есть заголовок, то в результате имеем ассоциативный массив +// $this->converter_conf['hasKey'] = 1; +// +// } +// +// } +//// $this->converter = \Yii::createObject( $this->converter_conf ); +// } + + } \ No newline at end of file diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index 0d74c94..8f2382f 100644 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -5,7 +5,7 @@ ['class' => 'common\components\parsers\CustomCsvParser', 'auto_detect_first_line' => true, 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', // @todo переделать на компонент + 'class' => 'common\components\parsers\CustomConverter', 'configuration' => ["encode" => 'DESCR'],] ], 'console' => @@ -13,7 +13,7 @@ 'auto_detect_first_line' => true, 'hasHeaderRow' => true, 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', + 'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => ["string" => 'DESCR', "float" => 'PRICE', @@ -42,7 +42,7 @@ 'hasHeaderRow' => true, 'keys' =>['ARTICLE', 'CROSS_ARTICLE', 'BRAND', 'CROSS_BRAND'], 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', + 'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => [ "brand" => ['BRAND', 'CROSS_BRAND'], @@ -55,7 +55,7 @@ ['class' => 'yii\multiparser\XmlParser', 'node' => 'Товар', 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', + 'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => ["details" => [] ],], diff --git a/common/config/main.php b/common/config/main.php index 42035f7..c4e33b0 100644 --- a/common/config/main.php +++ b/common/config/main.php @@ -15,14 +15,15 @@ return [ ] ], 'multiparser'=>[ - 'class' => 'yii\multiparser\YiiMultiparser', 'configuration' => $mp_configuration, - 'as behavior' => [ - 'class' => 'common\components\parsers\CustomConverter', + ], + 'converter'=>[ + 'class' => 'yii\multiparser\YiiConverter', + 'configuration' => [ + 'class' => 'common\components\parsers\CustomConverter' + ], ], ], - ], - ]; diff --git a/common/models/DetailsCurrency.php b/common/models/DetailsCurrency.php index 4a7960a..87ab9fa 100644 --- a/common/models/DetailsCurrency.php +++ b/common/models/DetailsCurrency.php @@ -6,7 +6,7 @@ use Yii; /** * This is the model class for table "{{%details_currency}}". - * + * w_details_currency - СПЕЦИАЛЬНО СОЗАДННАЯ ВЬЮШКА ДЛЯ ДОСТУПА К СПИСКУ ТОВАРОВ С ВАЛЮТАМИ И ИХ КУРСАМИ * @property string $ID * @property string $IMPORT_ID * @property string $BRAND -- libgit2 0.21.4