Blame view

backend/controllers/ParserController.php 8.01 KB
3cf42f5c   Mihail   init commit - bas...
1
2
3
4
5
  <?php
  namespace backend\controllers;
  
  use Yii;
  use yii\filters\AccessControl;
693c46cb   Mihail   add base classes ...
6
  use backend\components\base\BaseController;
3cf42f5c   Mihail   init commit - bas...
7
  use yii\filters\VerbFilter;
b13b1c83   Mihail   final version par...
8
  use backend\models\UploadFileParsingForm;
3cf42f5c   Mihail   init commit - bas...
9
  use yii\web\UploadedFile;
fcd9278e   Mihail   parser csv v1
10
  use yii\data\ArrayDataProvider;
74072a2a   Mihail   add first version...
11
  use yii\multiparser\DynamicFormHelper;
474f35bf   Mihail   add DynamicFormHe...
12
  use backend\components\parsers\CustomParserConfigurator;
8894c93a   Mihail   add Importers fil...
13
14
15
  use backend\models\Details;
  use backend\models\ImporterFiles;
  use yii\base\ErrorException;
500b481a   Administrator   JSON
16
  
e774f057   Mihail   work with custome...
17
  use common\components\CustomVarDamp;
3cf42f5c   Mihail   init commit - bas...
18
19
  
  /**
b13b1c83   Mihail   final version par...
20
   * Parser controller
3cf42f5c   Mihail   init commit - bas...
21
   */
693c46cb   Mihail   add base classes ...
22
  class ParserController extends BaseController
3cf42f5c   Mihail   init commit - bas...
23
  {
500b481a   Administrator   JSON
24
      public $layout = "/column";
8894c93a   Mihail   add Importers fil...
25
  
3cf42f5c   Mihail   init commit - bas...
26
27
28
29
30
31
32
33
34
35
      /**
       * @inheritdoc
       */
      public function behaviors()
      {
          return [
              'access' => [
                  'class' => AccessControl::className(),
                  'rules' => [
                      [
8894c93a   Mihail   add Importers fil...
36
                          'actions' => ['index', 'results', 'write'],
3cf42f5c   Mihail   init commit - bas...
37
38
39
40
41
                          'allow' => true,
                          'roles' => ['@'],
                      ],
                  ],
              ],
e774f057   Mihail   work with custome...
42
43
44
45
46
47
  //            'verbs' => [
  //                'class' => VerbFilter::className(),
  //                'actions' => [
  //                    'logout' => ['post'],
  //                ],
  //            ],
3cf42f5c   Mihail   init commit - bas...
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
          ];
      }
  
      /**
       * @inheritdoc
       */
      public function actions()
      {
          return [
              'error' => [
                  'class' => 'yii\web\ErrorAction',
              ],
          ];
      }
  
500b481a   Administrator   JSON
63
  
3cf42f5c   Mihail   init commit - bas...
64
65
      public function actionIndex()
      {
77422ce3   Mihail   edit upload form
66
          $model = new UploadFileParsingForm();
3cf42f5c   Mihail   init commit - bas...
67
  
500b481a   Administrator   JSON
68
69
70
          return $this->render('index', ['model' => $model]);
      }
  
8894c93a   Mihail   add Importers fil...
71
72
      public function actionResults()
      {
500b481a   Administrator   JSON
73
74
  
          $model = new UploadFileParsingForm();
474f35bf   Mihail   add DynamicFormHe...
75
          $data = [];
b13b1c83   Mihail   final version par...
76
          if ($model->load(Yii::$app->request->post())) {
3cf42f5c   Mihail   init commit - bas...
77
              $model->file = UploadedFile::getInstance($model, 'file');
8894c93a   Mihail   add Importers fil...
78
              // первый проход - валидируем, сохраняем файл, ложим в кеш отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
3663f570   Mihail   draft commit
79
              if ($model->validate()) {
fcd9278e   Mihail   parser csv v1
80
                  $filePath = Yii::getAlias('@webroot') . '/uploads/' . $model->file->baseName . '.' . $model->file->extension;
500b481a   Administrator   JSON
81
  
8894c93a   Mihail   add Importers fil...
82
83
                  $model->file->saveAs($filePath);
                  //запускаем парсинг
500b481a   Administrator   JSON
84
                  $data = $model->readFile($filePath);
8894c93a   Mihail   add Importers fil...
85
86
87
88
                  // сохраняем в кеш отпарсенные даные
                  Yii::$app->getCache()->set('parser_data', json_encode($data));
                  // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
                  Yii::$app->getCache()->set('parser_configuration', serialize($model));
500b481a   Administrator   JSON
89
  
500b481a   Administrator   JSON
90
  
3cf42f5c   Mihail   init commit - bas...
91
              }
8894c93a   Mihail   add Importers fil...
92
93
              // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
          } else if (Yii::$app->getCache()->get('parser_data')) {
500b481a   Administrator   JSON
94
  
8894c93a   Mihail   add Importers fil...
95
              $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
500b481a   Administrator   JSON
96
  
3cf42f5c   Mihail   init commit - bas...
97
98
          }
  
474f35bf   Mihail   add DynamicFormHe...
99
100
101
102
103
104
105
          $provider = new ArrayDataProvider([
              'allModels' => $data,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
  
8894c93a   Mihail   add Importers fil...
106
107
          //формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
          $header_model = DynamicFormHelper::CreateDynamicModel(count($data[0]));
474f35bf   Mihail   add DynamicFormHe...
108
  
474f35bf   Mihail   add DynamicFormHe...
109
110
111
          return $this->render('results',
              ['model' => $data,
                  'header_model' => $header_model,
8894c93a   Mihail   add Importers fil...
112
113
                  // список колонок для выбора
                  'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
474f35bf   Mihail   add DynamicFormHe...
114
                  'dataProvider' => $provider]);
3cf42f5c   Mihail   init commit - bas...
115
      }
474f35bf   Mihail   add DynamicFormHe...
116
  
8894c93a   Mihail   add Importers fil...
117
118
      public function actionWrite()
      {
474f35bf   Mihail   add DynamicFormHe...
119
  
8894c93a   Mihail   add Importers fil...
120
121
122
123
124
125
126
127
          //получим колонки которые выбрал пользователь
          $arr_attributes = Yii::$app->request->post()['DynamicModel'];
          //соберем модель по полученным данным
          $model = DynamicFormHelper::CreateDynamicModel($arr_attributes);
          //добавим правила валидации (колонки должны быть те что указаны в конфиге)
          foreach ($arr_attributes as $key => $value) {
              $model->addRule($key, 'in', ['range' => array_keys(Yii::$app->multiparser->getConfiguration('csv', 'basic_column'))]);
          }
474f35bf   Mihail   add DynamicFormHe...
128
  
8894c93a   Mihail   add Importers fil...
129
130
          // провалидируем выбранные колонки
          if ($model->validate()) {
28253169   Mihail   add converter as ...
131
  
8894c93a   Mihail   add Importers fil...
132
133
              // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
              $arr = $model->toArray();
aa518ad3   Mihail   finishing with co...
134
  
8894c93a   Mihail   add Importers fil...
135
136
137
138
139
140
141
              // получим данные из кеша
              if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) {
                  $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
                  $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration'));
              } else {
                  CustomVarDamp::dumpAndDie('Ошибка кеша');
              }
474f35bf   Mihail   add DynamicFormHe...
142
  
8894c93a   Mihail   add Importers fil...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
              // соотнесем отпарсенные данные с соответсивем полученным от пользователя
              // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
              $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_');
  
  
              // запишем дату старта в таблицу файлов поставщика (ImportersFiles)
              $files_model = new ImporterFiles();
              // id поставщика получим из конфигурации
              $files_model->load(['ImporterFiles' => $configuration->toArray()]);
              if ($files_model->validate()) {
                  try {
                      $files_model->save();
                  } catch (ErrorException  $e) {
                      CustomVarDamp::dump($e->getMessage());
                  }
  
  
                  // запишем полученные данные в таблицу товаров (Details)
                  $details_model = new Details('web');
                  // проверим все ли обязательные колонки были указаны пользователем
                  $details_model->load(['Details' => $data[0]]);
                  if ($details_model->validate()) {
                      // проставим импортера
                      $data = $details_model->prepareData($data, $configuration);
  
                      try {
                          // попытаемся вставить данные в БД с апдейтом по ключам
                          $details_model->save($data);
  
                          // а также зафиксируем дату конца загрузки
                          $files_model->time_end = mktime(); // ошибка!!!!!!!!!!!!!!!!
                          $files_model->save();
  
                          // все прошло успешно - очищаем кеш
                          Yii::$app->getCache()->delete('parser_data');
                          Yii::$app->getCache()->delete('parser_configuration');
  
                          CustomVarDamp::dumpAndDie('!!!');
                      } catch (ErrorException  $e) {
                          CustomVarDamp::dump($e->getMessage());
                      }
                  }
                  if ($details_model->hasErrors()) {
                      $errors_arr = $details_model->getErrors();
                      foreach ($errors_arr as $error) {
                          CustomVarDamp::dump(array_values($error));
                      }
  
                  }
474f35bf   Mihail   add DynamicFormHe...
192
  
3cf42f5c   Mihail   init commit - bas...
193
  
8894c93a   Mihail   add Importers fil...
194
195
196
197
198
199
              }
  
  
          }
  
      }
3cf42f5c   Mihail   init commit - bas...
200
201
  
  }