Commit d3cf66475275fb6fb337d9d7e1476c07fd3efd74

Authored by Mihail
1 parent e9b63b6a

add multiply price funktional in Converter

backend/controllers/ParserController.php
... ... @@ -266,13 +266,15 @@ class ParserController extends BaseController
266 266 foreach (glob(Yii::getAlias('@temp_upload') . '/*.csv') as $server_file) {
267 267  
268 268 $file_name = basename($server_file,".csv");
269   - // rename( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv');
270 269 copy( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv' );
271 270  
272 271 }
  272 +
273 273 Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' );
274 274 $this->redirect('server-files');
275 275  
  276 +// $csv = new \console\controllers\ParserController( 'parse-csv', $this->module );
  277 +// $csv->actionParseCsv();
276 278 }
277 279  
278 280  
... ...
backend/models/Importers.php
... ... @@ -2,6 +2,7 @@
2 2  
3 3 namespace backend\models;
4 4  
  5 +use common\components\CustomVarDamp;
5 6 use Yii;
6 7 use backend\components\base\BaseActiveRecord;
7 8  
... ... @@ -93,6 +94,7 @@ class Importers extends BaseActiveRecord
93 94 {
94 95 // возьмем только поля описанные в fields() - там как раз наши настройки парсера
95 96 $arr = $this->toArray();
  97 +
96 98 // отсортируем по ключам с учетом преобразования в число
97 99 asort($arr, SORT_NUMERIC);
98 100 // уберем нулевые колонки
... ... @@ -101,10 +103,21 @@ class Importers extends BaseActiveRecord
101 103 });
102 104 // нам нужны именно ключи
103 105 $arr = array_keys($arr);
  106 +
104 107 return $arr;
  108 + }
  109 +
  110 +
  111 + public function getMultiply ()
  112 + {
  113 + $arr['sign'] = $this->PARSER_FIELD_SIGN;
  114 + $arr['multiplier'] = $this->PARSER_FIELD_MULTIPLIER;
105 115  
  116 + return $arr;
106 117 }
107 118  
  119 +
  120 +
108 121 public function fields()
109 122 {
110 123 return [
... ... @@ -119,5 +132,4 @@ class Importers extends BaseActiveRecord
119 132  
120 133 }
121 134  
122   -
123 135 }
... ...
common/components/parsers/CustomConverter.php
... ... @@ -11,6 +11,9 @@ class CustomConverter extends Converter {
11 11 * @param $key_array - ключи для вложенного массива
12 12 * @return array - таблица с проименованными колонками
13 13 */
  14 + public static $sign;
  15 + public static $multiplier;
  16 +
14 17 public static function convertToAssocArray ( array $value_arr, array $key_array, $key_prefix = '' )
15 18 {
16 19 // очистка служебного префикса в массиве заголовков
... ... @@ -82,6 +85,40 @@ class CustomConverter extends Converter {
82 85 return $row;
83 86 }
84 87  
  88 + public function ConvertToMultiply ( array $row )
  89 + {
  90 + $PRICE = $row[ 'PRICE' ];
  91 + $sign = self::$sign;
  92 + $multiplier = self::$multiplier;
  93 + //CustomVarDamp::dumpAndDie(self);
  94 + if (isset($sign)) {
  95 + if ($sign == '+') {
  96 + if ($multiplier > 0) {
  97 + $PRICE += $multiplier;
  98 + }
  99 + }
  100 + else if ($sign == '-') {
  101 + if ($multiplier > 0) {
  102 + $PRICE -= $multiplier;
  103 + }
  104 + }
  105 + else if ($sign == '*') {
  106 + if ($multiplier > 0) {
  107 + $PRICE *= $multiplier;
  108 + }
  109 + }
  110 + else if ($sign == '/') {
  111 + if ($multiplier > 0) {
  112 + $PRICE /= $multiplier;
  113 + }
  114 + }
  115 + }
  116 +
  117 + $row[ 'PRICE' ] = $PRICE;
  118 +
  119 + return $row;
  120 +
  121 + }
85 122  
86 123  
87 124 }
88 125 \ No newline at end of file
... ...
common/components/parsers/CustomCsvParser.php
... ... @@ -25,10 +25,12 @@ class CustomCsvParser extends \yii\multiparser\CsvParser {
25 25 if ($this->hasHeaderRow) {
26 26 // если у файла есть заголовок, то в результате имеем ассоциативный массив
27 27 $this->converter_conf['hasKey'] = 1;
  28 +
28 29 }
29 30  
30 31 }
31   -
  32 +// $this->converter = \Yii::createObject( $this->converter_conf );
  33 +// CustomVarDamp::dumpAndDie($this->converter);
32 34 }
33 35  
34 36 /**
... ... @@ -38,7 +40,7 @@ class CustomCsvParser extends \yii\multiparser\CsvParser {
38 40 */
39 41 protected function convert($arr)
40 42 {
41   - $arr = \Yii::$app->multiparser->convertByConfiguration($arr, $this->converter_conf);
  43 + $arr = \Yii::$app->multiparser->convertByConfiguration( $arr, $this->converter_conf );
42 44  
43 45 return $arr;
44 46  
... ...
common/components/parsers/config.php
... ... @@ -4,18 +4,21 @@
4 4 ['web' =>
5 5 ['class' => 'common\components\parsers\CustomCsvParser',
6 6 'auto_detect_first_line' => true,
7   - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter',
  7 + 'converter_conf' => [
  8 + //'class' => ' common\components\parsers\CustomConverter', // @todo переделать на подключаемый behavior
8 9 'configuration' => ["string" => 'DESCR'],]
9 10 ],
10 11 'console' =>
11 12 ['class' => 'common\components\parsers\CustomCsvParser',
12 13 'auto_detect_first_line' => true,
13 14 'hasHeaderRow' => true,
14   - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter',
  15 + 'converter_conf' => [
  16 + //'class' => ' common\components\parsers\CustomConverter',
15 17 'hasKey' => 1,
16 18 'configuration' => ["string" => 'DESCR',
17 19 "float" => 'PRICE',
18 20 "integer" => ['BOX','ADD_BOX'],
  21 + "multiply" => [],
19 22 "details" => [] // @todo сделать отдельно конфигурирование валидации
20 23  
21 24 ]
... ... @@ -36,7 +39,8 @@
36 39 ['console' =>
37 40 ['class' => 'yii\multiparser\XmlParser',
38 41 'node' => 'Товар',
39   - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter',
  42 + 'converter_conf' => [
  43 + //'class' => ' common\components\parsers\CustomConverter',
40 44 'hasKey' => 1,
41 45 'configuration' => ["details" => []
42 46 ],],
... ...
console/controllers/ParserController.php
1 1 <?php
2 2 namespace console\controllers;
3 3  
  4 +use common\components\CustomVarDamp;
4 5 use yii\console\Controller;
5 6 use yii\helpers\Console;
6 7 use common\components\PriceWriter;
... ... @@ -10,7 +11,6 @@ use yii\base\ErrorException;
10 11  
11 12 class ParserController extends Controller
12 13 {
13   -
14 14 public function actionParseCsv()
15 15 {
16 16 \Yii::info('Начало загрузки файлов прайсов csv', 'parser');
... ... @@ -18,11 +18,22 @@ class ParserController extends Controller
18 18 $file_name = basename($file_path, ".csv");
19 19 \Yii::info("Обработка файла - $file_path", 'parser');
20 20 $importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id;
21   - $keys = Importers::findOne(['id' => $importer_id])->keys;
  21 + $current_importer = Importers::findOne(['id' => $importer_id]);
  22 + $keys = $current_importer->keys;
  23 + $mult_array = $current_importer->multiply;
  24 +
  25 + // получим настройки ценообразования и передадим их отдельно в конвертер
  26 + $sign = '';
  27 + $multiplier = '';
  28 + extract( $mult_array );
  29 +
22 30  
23 31 $config = ['record_id' => $file_name,
24 32 'importer_id' => $importer_id,
25 33 'parser_config' => ['keys' => $keys,
  34 + 'converter_conf' =>
  35 + ['sign' => $sign,
  36 + 'multiplier' => $multiplier],
26 37 'mode' => 'console']
27 38 ];
28 39 if ($this->parseFileConsole($file_path, $config)) {
... ... @@ -48,7 +59,7 @@ class ParserController extends Controller
48 59 $parser_config = $configuration['parser_config'];
49 60 }
50 61 $data = \Yii::$app->multiparser->parse( $file_path, $parser_config );
51   - if (! $data) {
  62 + if ( ! $data ) {
52 63 // @todo переделать, что бы ошибка автоматически останавливала сценарий
53 64 return false;
54 65 }
... ...
vendor/yiisoft/multiparser/Converter.php
... ... @@ -9,6 +9,7 @@
9 9 namespace yii\multiparser;
10 10 use common\components\CustomVarDamp;
11 11 use yii\base\Behavior;
  12 +use yii\base\ErrorException;
12 13  
13 14 // класс который содержит преобразователи значений (фильтры) используемые при парсинге
14 15 class Converter extends Behavior
... ... @@ -98,8 +99,23 @@ class Converter extends Behavior
98 99 */
99 100 public static function convertByConfiguration( $arr, $configuration )
100 101 {
101   - $hasKey = isset( $configuration['hasKey'] );
102   - foreach ( $configuration['configuration'] as $key => $value ) {
  102 + if( $hasKey = isset( $configuration['hasKey'] ) )
  103 + unset( $configuration['hasKey'] );
  104 +
  105 + if ( isset( $configuration['configuration'] ) ) {
  106 + $arr_config = $configuration['configuration'];
  107 + unset( $configuration['configuration'] );
  108 + } else{
  109 + throw new ErrorException('Не указан обязательный параметр конфигурационного файла - converter_conf[configuration]');
  110 + }
  111 +
  112 + // проставим аттрибуды из конфига{}{}
  113 + foreach ($configuration as $key_setting => $setting) {
  114 + if( property_exists( static::class, $key_setting ) )
  115 + static::$$key_setting = $setting;
  116 + }
  117 +
  118 + foreach ( $arr_config as $key => $value ) {
103 119 if ( $hasKey ){
104 120 // у нас ассоциативный массив, и мы можем конвертировать каждое значение в отдельности
105 121 if ( is_array( $value ) ) {
... ...
vendor/yiisoft/multiparser/CsvParser.php
... ... @@ -50,6 +50,8 @@ class CsvParser implements ParserInterface
50 50 public $converter_conf = [];
51 51 /** @var array - конвертер созданный по конфигурации */
52 52 public $converter = NULL;
  53 + /** @var int - текущая строка */
  54 + private $current_line = 0;
53 55  
54 56  
55 57 /**
... ... @@ -95,8 +97,9 @@ class CsvParser implements ParserInterface
95 97 {
96 98  
97 99 $finish = false;
98   -
99 100 while (!$finish) {
  101 + $this->current_line ++;
  102 +
100 103 $j = 0;
101 104 $row = $this->file->fgetcsv();;
102 105 if ($row === false) {
... ... @@ -104,6 +107,7 @@ class CsvParser implements ParserInterface
104 107 }
105 108  
106 109 for ($i = 1; $i <= count($row); $i++) {
  110 + // CustomVarDamp::dump($row[$i]);
107 111  
108 112 if ($row[$i - 1] <> '') {
109 113 $j++;
... ... @@ -114,6 +118,9 @@ class CsvParser implements ParserInterface
114 118 }
115 119 }
116 120 }
  121 + die();
  122 + // $this->current_line --;
  123 + $this->file->seek( $this->current_line );
117 124 }
118 125  
119 126 /**
... ... @@ -125,12 +132,11 @@ class CsvParser implements ParserInterface
125 132  
126 133 $return = [];
127 134  
128   - $current_line = 0;
129 135 // будем считать количество пустых строк подряд - при трех подряд - считаем что это конец файла и выходим
130 136 $empty_lines = 0;
131 137 while ( $empty_lines < 3 ) {
132 138 // прочтем строку из файла. Если там есть значения - то в ней массив, иначе - false
133   - $row = $this->readRow( $current_line );
  139 + $row = $this->readRow( );
134 140  
135 141 if ($row === false) {
136 142 //счетчик пустых строк
... ... @@ -138,7 +144,7 @@ class CsvParser implements ParserInterface
138 144 continue;
139 145 }
140 146 // строка не пустая, имеем прочитанный массив значений
141   - $current_line++;
  147 + $this->current_line++;
142 148 if ($this->hasHeaderRow) {
143 149 // в файле есть заголовок, но он еще не назначен, назначим
144 150 if ($this->keys === NULL) {
... ... @@ -146,7 +152,7 @@ class CsvParser implements ParserInterface
146 152 }
147 153 }
148 154 // если у нас установлен лимит, при его достижении прекращаем парсинг
149   - if (($this->last_line) && ($current_line > $this->last_line)) {
  155 + if (($this->last_line) && ($this->current_line > $this->last_line)) {
150 156 break;
151 157 }
152 158 // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД
... ... @@ -168,16 +174,19 @@ class CsvParser implements ParserInterface
168 174 /**
169 175 * @return array - одномерный массив результата парсинга строки
170 176 */
171   - protected function readRow( $current_line )
  177 + protected function readRow( )
172 178 {
173 179 $row = $this->file->fgetcsv();
  180 + // уберем нулевые колонки
  181 + $row = array_filter($row, function($val){
  182 + return $val <> '';
  183 + });
174 184 if (is_array($row)) {
175 185 // если есть заголовок, то перед конвертацией его нужно назначить
176 186 if ($this->hasHeaderRow && $this->keys !== NULL) {
177 187  
178 188 if (count($this->keys) !== count($row)) {
179   -//
180   - throw new \ErrorException("Ошибка парсинга файла в строке # {$current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $current_line);
  189 + throw new \ErrorException("Ошибка парсинга файла в строке # {$this->current_line}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными", 0, 1, $this->file->getBasename(), $this->current_line);
181 190 }
182 191  
183 192 $row = array_combine($this->keys, $row);
... ...
vendor/yiisoft/multiparser/YiiParserHandler.php
... ... @@ -9,6 +9,8 @@
9 9 namespace yii\multiparser;
10 10  
11 11  
  12 +use common\components\CustomVarDamp;
  13 +
12 14 class YiiParserHandler extends ParserHandler{
13 15  
14 16  
... ... @@ -46,8 +48,7 @@ class YiiParserHandler extends ParserHandler{
46 48  
47 49 try {
48 50 $this->configuration = \Yii::$app->multiparser->getConfiguration($this->extension, $this->mode);
49   - $this->configuration = array_merge($this->configuration, $options);
50   -
  51 + $this->configuration = array_merge_recursive ($this->configuration, $options);
51 52 } catch (\ErrorException $e) {
52 53 echo $e->getMessage();
53 54 return [];
... ...