Commit 2a7a75b8ebfa7b2a080712b9b35bbcd39cf84234

Authored by Mihail
1 parent 7a80e74c

add first version XML parser, add CSVconverter

backend/components/parsers/CustomCsvParser.php
@@ -14,20 +14,19 @@ class CustomCsvParser extends \yii\multiparser\CsvParser { @@ -14,20 +14,19 @@ class CustomCsvParser extends \yii\multiparser\CsvParser {
14 //public $last_line = 10; 14 //public $last_line = 10;
15 //public $hasHeaderRow = true; 15 //public $hasHeaderRow = true;
16 // public $keys = ['first','second', 'third', 'forth', 'fifth']; 16 // public $keys = ['first','second', 'third', 'forth', 'fifth'];
17 -  
18 -  
19 - protected function readRow() 17 + public function setupConverter()
20 { 18 {
21 19
22 - $row = parent::readRow();  
23 20
24 - if (is_array($row)) {  
25 -  
26 - $row = Encoder::encodeArray( Encoder::$in_charset, Encoder::$out_charset, $row ); 21 + if ($this->hasHeaderRow) {
  22 + // если у файла есть заголовок, то в результате имеем ассоциативный массив
  23 + $this->converter_conf['hasKey'] = 1;
27 } 24 }
28 25
29 - return $row; 26 + $this->converter = \Yii::createObject($this->converter_conf);
  27 + \common\components\CustomVarDamp::dumpAndDie($this);
30 28
31 } 29 }
32 30
  31 +
33 } 32 }
34 \ No newline at end of file 33 \ No newline at end of file
backend/components/parsers/CustomParserConfigurator.php deleted
1 -<?php  
2 -  
3 -namespace backend\components\parsers;  
4 -use yii\multiparser\ParserConfigurator;  
5 -  
6 -class CustomParserConfigurator extends ParserConfigurator  
7 -{  
8 -  
9 - protected static $configuration = [  
10 - 'csv' =>  
11 - ['web' =>  
12 - ['class' => 'backend\components\parsers\CustomCsvParser',  
13 - 'auto_detect_first_line' => true,]]];  
14 -  
15 -  
16 -  
17 - public static $basic_column = [  
18 - "BRAND" => 'Бренд',  
19 - "ARTICLE"=> 'Артикул',  
20 - "PRICE" => 'Цена',  
21 - "DESCR" => 'Наименование',  
22 - "BOX" => 'Колво',  
23 - "ADD_BOX"=> 'В пути',  
24 - "GROUP" => 'Группа RG'  
25 - ];  
26 -  
27 -  
28 -}  
29 \ No newline at end of file 0 \ No newline at end of file
backend/components/parsers/DynamicFormHelper.php deleted
1 -<?php  
2 -/**  
3 - * Created by PhpStorm.  
4 - * User: Cibermag  
5 - * Date: 08.09.2015  
6 - * Time: 14:50  
7 - */  
8 -  
9 -namespace backend\components\parsers;  
10 -  
11 -use yii\base\DynamicModel;  
12 -use yii\grid\GridView;  
13 -use yii\grid\SerialColumn;  
14 -  
15 -/**  
16 - * Class DynamicFormHelper  
17 - * @package backend\components\parsers  
18 - * Содержит процедуры генерации компонентов с динамическим количеством аттрибутов  
19 - */  
20 -class DynamicFormHelper  
21 -{  
22 -  
23 -  
24 - /**  
25 - * @param $source - int or array  
26 - * если передан массив, то создается модель с атрибутами переданными в массиве,  
27 - * ключ - имя, значение - значение аттрибута  
28 - * если передано число, то создается переданное количество аттрибутов с именами - attr_0, attr_1...  
29 - */  
30 - public static function CreateDynamicModel($source)  
31 - {  
32 - $arr_keys = [];  
33 - if (is_array($source)) {  
34 - $arr_keys = $source;  
35 - } elseif (is_int($source)) {  
36 -  
37 - $i = 0;  
38 - while ($source > $i) {  
39 - $arr_keys[] = "attr_{$i}";  
40 - $i++;  
41 - }  
42 - array_flip($arr_keys);  
43 -  
44 - }  
45 -  
46 - $model = new DynamicModel($arr_keys);  
47 -  
48 - return $model;  
49 - }  
50 -  
51 - // @todo - rewrite on two functions, add comments  
52 - public static function CreateDynamicGridViewWithDropDownListHeader( $dataProvider, $form, $header_model, $arr_header_values )  
53 - {  
54 - $columns_config = [['class' => SerialColumn::className()]];  
55 - $i = 0;  
56 - foreach( $header_model as $key => $value ) {  
57 -  
58 - $columns_config[] = ['header' => $form->field($header_model, $key, ['inputOptions' => ['label' => '']])->dropDownList($arr_header_values), 'attribute' => $i];  
59 - $i++;  
60 - }  
61 -  
62 - //\common\components\CustomVarDamp::dumpAndDie($columns_config);  
63 -  
64 - $dynamic_grid_view = GridView::widget( ['dataProvider' => $dataProvider,  
65 - 'columns' => $columns_config ] );  
66 -  
67 - return $dynamic_grid_view;  
68 -  
69 - }  
70 -  
71 -  
72 -  
73 -}  
74 \ No newline at end of file 0 \ No newline at end of file
backend/components/parsers/Encoder.php deleted
1 -<?php  
2 -/**  
3 - * Created by PhpStorm.  
4 - * User: Cibermag  
5 - * Date: 27.08.2015  
6 - * Time: 13:36  
7 - */  
8 -  
9 -namespace backend\components\parsers;  
10 -  
11 -// @todo add comments  
12 -class Encoder  
13 -{  
14 - /** @var out encoding charset */  
15 - public static $out_charset = 'UTF-8';  
16 - /** @var out encoding charset */  
17 - public static $in_charset = 'windows-1251';  
18 -  
19 - public static function encodeFile($in_charset, $out_charset, $filePath)  
20 - {  
21 -  
22 - $old_content = file_get_contents($filePath);  
23 - $encode_content = self::encode( $in_charset, $out_charset, $old_content );  
24 - $file = @fopen($filePath, "w");  
25 - fwrite($file, $encode_content);  
26 - @fclose($file);  
27 - }  
28 -  
29 - public static function encodeArray($in_charset, $out_charset, $array)  
30 - {  
31 -  
32 - self::$in_charset = $in_charset;  
33 - self::$out_charset = $out_charset;  
34 -  
35 - $result = array_map(  
36 - function ( $array) {  
37 -  
38 - return self::encode( self::$in_charset, self::$out_charset, $array );  
39 -  
40 - },  
41 - $array);  
42 -  
43 - return $result;  
44 - }  
45 -  
46 - private static function encode( $in_charset, $out_charset, $source ){  
47 -  
48 - return iconv($in_charset, $out_charset, $source);  
49 -  
50 - }  
51 -}  
52 \ No newline at end of file 0 \ No newline at end of file
backend/components/parsers/ValueFilter.php deleted
1 -<?php  
2 -/**  
3 - * Created by PhpStorm.  
4 - * User: Cibermag  
5 - * Date: 31.08.2015  
6 - * Time: 12:50  
7 - */  
8 -  
9 -namespace backend\components\parsers;  
10 -  
11 -// класс который содержит преобразователи значений (фильтры) используемые при парсинге  
12 -class ValueFilter  
13 -{  
14 -  
15 - public static function pricefilter($str)  
16 - {  
17 - if ($str == '') {  
18 - $str = 0;  
19 - }  
20 - $str = trim(str_replace(",", ".", $str));  
21 - $str = preg_replace("/[^0-9.]+/", "", strtoupper($str));  
22 -  
23 - if ($str == '') {  
24 - return '';  
25 - }  
26 - $str = round( (float)$str, 2 );  
27 -  
28 - return $str;  
29 - }  
30 -  
31 - public static function boxfilter($str)  
32 - {  
33 - if ($str == '') {  
34 - $str = 0;  
35 - }  
36 - $str = trim(str_replace(",", ".", $str));  
37 - $str = preg_replace("/[^0-9.]+/", "", strtoupper($str));  
38 - if ($str == '') {  
39 - return '';  
40 - }  
41 - $str = round((int)$str, 2);  
42 -  
43 - return $str;  
44 - }  
45 -}  
46 \ No newline at end of file 0 \ No newline at end of file
backend/components/parsers/config.php 0 → 100644
  1 +<?php
  2 + return [
  3 + 'csv' =>
  4 + ['web' =>
  5 + ['class' => 'backend\components\parsers\CustomCsvParser',
  6 + 'auto_detect_first_line' => true,
  7 + 'converter_conf' => ['class' => 'yii\multiparser\CsvConverter',
  8 + 'configuration' => [
  9 + "string" => 'DESCR'
  10 + ]
  11 + ,]],
  12 +
  13 + 'basic_column' => [
  14 + "BRAND" => 'Бренд',
  15 + "ARTICLE"=> 'Артикул',
  16 + "PRICE" => 'Цена',
  17 + "DESCR" => 'Наименование',
  18 + "BOX" => 'Колво',
  19 + "ADD_BOX"=> 'В пути',
  20 + "GROUP" => 'Группа RG'
  21 + ],
  22 + ]];
  23 +
  24 +
  25 +//[
  26 +// "float" => 'PRICE',
  27 +// "integer" => ['BOX' , 'ADD_BOX' ],
  28 +// "prefix" => 'ARTICLE'
  29 +//]
0 \ No newline at end of file 30 \ No newline at end of file
backend/config/main.php
@@ -5,6 +5,7 @@ $params = array_merge( @@ -5,6 +5,7 @@ $params = array_merge(
5 require(__DIR__ . '/params.php'), 5 require(__DIR__ . '/params.php'),
6 require(__DIR__ . '/params-local.php') 6 require(__DIR__ . '/params-local.php')
7 ); 7 );
  8 +$mp_configuration = require( __DIR__ . '/../components/parsers/config.php');
8 9
9 return [ 10 return [
10 'id' => 'app-backend', 11 'id' => 'app-backend',
@@ -41,6 +42,7 @@ return [ @@ -41,6 +42,7 @@ return [
41 'multiparser'=>[ 42 'multiparser'=>[
42 43
43 'class' => 'yii\multiparser\YiiMultiparser', 44 'class' => 'yii\multiparser\YiiMultiparser',
  45 + 'configuration' => $mp_configuration,
44 46
45 ], 47 ],
46 ], 48 ],
backend/controllers/ParserController.php
@@ -8,7 +8,7 @@ use yii\filters\VerbFilter; @@ -8,7 +8,7 @@ use yii\filters\VerbFilter;
8 use backend\models\UploadFileParsingForm; 8 use backend\models\UploadFileParsingForm;
9 use yii\web\UploadedFile; 9 use yii\web\UploadedFile;
10 use yii\data\ArrayDataProvider; 10 use yii\data\ArrayDataProvider;
11 -use backend\components\parsers\DynamicFormHelper; 11 +use yii\multiparser\DynamicFormHelper;
12 use backend\components\parsers\CustomParserConfigurator; 12 use backend\components\parsers\CustomParserConfigurator;
13 13
14 use common\components\CustomVarDamp; 14 use common\components\CustomVarDamp;
@@ -96,13 +96,14 @@ class ParserController extends BaseController @@ -96,13 +96,14 @@ class ParserController extends BaseController
96 ], 96 ],
97 ]); 97 ]);
98 98
  99 + // CustomVarDamp::dumpAndDie($data);
99 $header_model = DynamicFormHelper::CreateDynamicModel( count( $data[0] ) ); 100 $header_model = DynamicFormHelper::CreateDynamicModel( count( $data[0] ) );
100 101
101 - //CustomVarDamp::dumpAndDie($header_model); 102 + // CustomVarDamp::dumpAndDie(Yii::$app->multiparser->getConfiguration('csv','basic_column'));
102 return $this->render('results', 103 return $this->render('results',
103 ['model' => $data, 104 ['model' => $data,
104 'header_model' => $header_model, 105 'header_model' => $header_model,
105 - 'basic_column' => CustomParserConfigurator::$basic_column, 106 + 'basic_column' => Yii::$app->multiparser->getConfiguration('csv','basic_column'),
106 'dataProvider' => $provider]); 107 'dataProvider' => $provider]);
107 } 108 }
108 109
@@ -113,7 +114,7 @@ public function actionWrite() @@ -113,7 +114,7 @@ public function actionWrite()
113 $arr_attributes = Yii::$app->request->post()['DynamicModel']; 114 $arr_attributes = Yii::$app->request->post()['DynamicModel'];
114 $model = DynamicFormHelper::CreateDynamicModel( $arr_attributes ); 115 $model = DynamicFormHelper::CreateDynamicModel( $arr_attributes );
115 foreach ($arr_attributes as $key => $value) { 116 foreach ($arr_attributes as $key => $value) {
116 - $model->addRule($key, 'in', ['range' => array_keys( CustomParserConfigurator::$basic_column )]); 117 + $model->addRule($key, 'in', ['range' => array_keys( Yii::$app->multiparser->getConfiguration('csv','basic_column') )]);
117 } 118 }
118 119
119 //CustomVarDamp::dumpAndDie($model); 120 //CustomVarDamp::dumpAndDie($model);
backend/views/parser/results.php
1 <?php 1 <?php
2 2
3 use yii\helpers\Html; 3 use yii\helpers\Html;
4 -use backend\components\parsers\DynamicFormHelper; 4 +use yii\multiparser\DynamicFormHelper;
5 use yii\widgets\ActiveForm; 5 use yii\widgets\ActiveForm;
6 6
7 7
@@ -20,7 +20,7 @@ $this-&gt;params[&#39;breadcrumbs&#39;][] = $this-&gt;title; @@ -20,7 +20,7 @@ $this-&gt;params[&#39;breadcrumbs&#39;][] = $this-&gt;title;
20 20
21 $form = ActiveForm::begin(['action' => 'write']); 21 $form = ActiveForm::begin(['action' => 'write']);
22 ?> 22 ?>
23 - <?= DynamicFormHelper::CreateDynamicGridViewWithDropDownListHeader( $dataProvider, $form, $header_model, $basic_column )?> 23 + <?= DynamicFormHelper::CreateGridWithDropDownListHeader( $dataProvider, $form, $header_model, $basic_column )?>
24 24
25 <div class="form-group"> 25 <div class="form-group">
26 <?= Html::submitButton(Yii::t('app', 'Записать в БД'), ['class' => 'btn btn-primary']) ?> 26 <?= Html::submitButton(Yii::t('app', 'Записать в БД'), ['class' => 'btn btn-primary']) ?>