7776ca75
Mihail
add form, model a...
|
1
2
3
4
5
6
7
8
9
10
|
<?php
/**
* Created by PhpStorm.
* User: Tsurkanov
* Date: 15.10.2015
* Time: 12:27
*/
namespace backend\controllers;
|
d11ec8b2
Mihail
fixed permissions...
|
11
|
use backend\components\base\BaseActiveRecord;
|
7776ca75
Mihail
add form, model a...
|
12
|
use backend\components\base\BaseController;
|
058dbbcc
Mihail
change writing cr...
|
13
|
use common\components\CustomArrayHelper;
|
7776ca75
Mihail
add form, model a...
|
14
|
use common\components\CustomVarDamp;
|
e323ebc1
Mihail
fixed issues with...
|
15
|
use yii\base\ErrorException;
|
d11ec8b2
Mihail
fixed permissions...
|
16
|
use yii\base\Model;
|
22fcf59f
Mihail
add form result f...
|
17
|
use yii\data\ArrayDataProvider;
|
d11ec8b2
Mihail
fixed permissions...
|
18
|
use yii\db\ActiveRecord;
|
a8808843
Administrator
access in admin
|
19
|
use yii\filters\VerbFilter;
|
7776ca75
Mihail
add form, model a...
|
20
21
22
|
use yii\filters\AccessControl;
use backend\models\UploadFileCrossingForm;
use backend\models\DetailsCrosses;
|
22fcf59f
Mihail
add form result f...
|
23
|
use yii\multiparser\DynamicFormHelper;
|
7776ca75
Mihail
add form, model a...
|
24
25
26
27
28
29
30
|
use yii\web\UploadedFile;
use \Yii;
class CrossingUploadController extends BaseController
{
public $layout = "/column";
|
a8808843
Administrator
access in admin
|
31
|
|
058dbbcc
Mihail
change writing cr...
|
32
33
34
35
|
/**
* @inheritdoc
*/
public function behaviors()
|
7776ca75
Mihail
add form, model a...
|
36
37
38
39
40
41
|
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
|
058dbbcc
Mihail
change writing cr...
|
42
|
'actions' => ['result', 'index', 'write'],
|
7776ca75
Mihail
add form, model a...
|
43
44
45
46
47
|
'allow' => true,
'roles' => ['@'],
],
],
],
|
a8808843
Administrator
access in admin
|
48
49
50
51
52
53
|
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
|
7776ca75
Mihail
add form, model a...
|
54
55
|
];
}
|
058dbbcc
Mihail
change writing cr...
|
56
|
|
7776ca75
Mihail
add form, model a...
|
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionIndex()
{
$model = new UploadFileCrossingForm();
return $this->render('index', ['model' => $model]);
}
public function actionResult()
{
$model = new UploadFileCrossingForm();
$data = [];
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
|
7776ca75
Mihail
add form, model a...
|
82
83
84
|
if ($model->validate()) {
$file_name = $model->file->name;
$model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name;
|
7776ca75
Mihail
add form, model a...
|
85
86
|
$model->file->saveAs($model->file_path);
//запускаем парсинг
|
22fcf59f
Mihail
add form result f...
|
87
88
|
$data = $model->readFile();
// сохраняем в кеш отпарсенные даные
|
d11ec8b2
Mihail
fixed permissions...
|
89
|
$this->cacheHandler( 1, $data, $model );
|
22fcf59f
Mihail
add form result f...
|
90
|
} else if (Yii::$app->getCache()->get('parser_data')) {
|
22fcf59f
Mihail
add form result f...
|
91
|
$data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
|
22fcf59f
Mihail
add form result f...
|
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
}
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
// создадим модель на столько реквизитов сколько колонок в отпарсенном файле
$last_index = end(array_flip($data[0]));
$header_counts = $last_index + 1;
$header_model = DynamicFormHelper::CreateDynamicModel($header_counts);
// соберем массив данных из которых будет пользователь выбирать значения в конструкторе (выпадающий список)
$basicColumns = $this->getBasicColumns();
return $this->render('results',
['model' => $data,
'header_model' => $header_model,
// список колонок для выбора
'basic_column' => $basicColumns,
'dataProvider' => $provider]);
}
}
|
22fcf59f
Mihail
add form result f...
|
117
118
119
120
121
122
123
124
|
public function actionWrite()
{
//получим колонки которые выбрал пользователь
$arr_attributes = Yii::$app->request->post()['DynamicModel'];
//соберем модель по полученным данным
$model = DynamicFormHelper::CreateDynamicModel($arr_attributes);
//добавим правила валидации (колонки должны быть те что в модели)
foreach ($arr_attributes as $key => $value) {
|
058dbbcc
Mihail
change writing cr...
|
125
|
$model->addRule($key, 'in', [ 'range' => array_keys( $this->getBasicColumns() ) ]);
|
22fcf59f
Mihail
add form result f...
|
126
127
128
|
}
// провалидируем выбранные колонки
|
e323ebc1
Mihail
fixed issues with...
|
129
|
if ( $model->validate() ) {
|
22fcf59f
Mihail
add form result f...
|
130
131
132
133
134
|
// валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
$arr = $model->toArray();
// получим данные из кеша
|
d11ec8b2
Mihail
fixed permissions...
|
135
|
$this->cacheHandler( 0, $data, $configuration );
|
22fcf59f
Mihail
add form result f...
|
136
137
138
139
140
|
// соотнесем отпарсенные данные с соответствием полученным от пользователя
// для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
$data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_');
|
058dbbcc
Mihail
change writing cr...
|
141
142
|
// запустим конвертер над над данными
$data = $this->convertDataByConfiguration( $data, $configuration );
|
22fcf59f
Mihail
add form result f...
|
143
|
|
058dbbcc
Mihail
change writing cr...
|
144
|
$crosses_model = new DetailsCrosses();
|
22fcf59f
Mihail
add form result f...
|
145
|
|
e323ebc1
Mihail
fixed issues with...
|
146
|
if ( $crosses_model->ManualInsertWithIgnore( $data ) ) {
|
d11ec8b2
Mihail
fixed permissions...
|
147
148
149
150
151
152
153
154
155
156
157
|
Yii::$app->session->setFlash('success', 'Файл кроссов успешно загружен');
// очистим кеш
$this->cacheHandler( 2 );
if (file_exists($configuration['file_path']))
unlink($configuration['file_path']);
return $this->render('index', ['model' => $configuration]);
}
|
22fcf59f
Mihail
add form result f...
|
158
|
|
7776ca75
Mihail
add form, model a...
|
159
|
|
058dbbcc
Mihail
change writing cr...
|
160
|
} else {
|
e323ebc1
Mihail
fixed issues with...
|
161
|
// не прошла валидация формы загрузки файлов
|
058dbbcc
Mihail
change writing cr...
|
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
|
$errors_str = '';
foreach ($model->getErrors() as $error) {
$errors_str .= implode(array_values($error));
}
throw new \ErrorException($errors_str);
}
}
protected function getBasicColumns()
{
$basicColumns_array = Yii::$app->multiparser->getConfiguration('csv', 'crosses');
if (isset($basicColumns_array['basic_column'])) {
return $basicColumns_array['basic_column'];
} else {
throw new \ErrorException('Ошибка конфигурационного файла кроссов. Не указаны базовые колнки для пользовательской формы выбора.');
|
7776ca75
Mihail
add form, model a...
|
177
|
}
|
22fcf59f
Mihail
add form result f...
|
178
|
|
7776ca75
Mihail
add form, model a...
|
179
|
}
|
b846d5f9
Mihail
add expiration ti...
|
180
|
|
058dbbcc
Mihail
change writing cr...
|
181
182
183
184
185
186
187
188
189
190
191
192
|
protected function convertDataByConfiguration( $data, $configuration ){
// доп. опции для парсера - удаление префикса в артикулах
$options['mode'] = 'crosses';
$fields = [];
if ($configuration['delete_prefix1']) {
$fields[] = 'ARTICLE';
}
if ($configuration['delete_prefix2']) {
$fields[] = 'CROSS_ARTICLE';
}
if ($fields) {
|
e323ebc1
Mihail
fixed issues with...
|
193
|
$options ['converter_conf']['configuration'] = ["article" => $fields,
|
058dbbcc
Mihail
change writing cr...
|
194
195
|
"string" => ['ARTICLE', 'CROSS_ARTICLE'],];
} else {
|
e323ebc1
Mihail
fixed issues with...
|
196
|
$options ['converter_conf']['configuration'] = ["string" => ['ARTICLE', 'CROSS_ARTICLE'],];
|
058dbbcc
Mihail
change writing cr...
|
197
198
|
}
|
e323ebc1
Mihail
fixed issues with...
|
199
200
201
202
203
204
205
|
// получим базовую конфигурацию и объеденим её с той что образовалась после выбора пользователем настроек
$basic_options = Yii::$app->multiparser->getConfiguration( 'csv', 'crosses' );
$options = array_merge_recursive( $options, $basic_options );
// для доп массива обратных строк
$i = count( $data ) - 1;
$reverse_data = [];
|
d11ec8b2
Mihail
fixed permissions...
|
206
|
foreach ( $data as &$row ) {
|
e323ebc1
Mihail
fixed issues with...
|
207
208
209
210
211
212
213
|
$row = Yii::$app->converter->convertByConfiguration( $row, $options['converter_conf'] );
// нужно добавить обратную строку по кроссам
$reverse_data[ $i ]['ARTICLE'] = $row['CROSS_ARTICLE'];
$reverse_data[ $i ]['CROSS_ARTICLE'] = $row['ARTICLE'];
$reverse_data[ $i ]['BRAND'] = $row['CROSS_BRAND'];
$reverse_data[ $i ]['CROSS_BRAND'] = $row['BRAND'];
$i++;
|
058dbbcc
Mihail
change writing cr...
|
214
215
|
}
|
e323ebc1
Mihail
fixed issues with...
|
216
|
$data = array_merge( $data, $reverse_data );
|
058dbbcc
Mihail
change writing cr...
|
217
218
219
220
221
|
return $data;
}
/**
|
d11ec8b2
Mihail
fixed permissions...
|
222
|
* @param $mode - int: 0 - fetch from cache, - 1 - put in cache, <2 - delete from cache
|
058dbbcc
Mihail
change writing cr...
|
223
224
225
226
|
* @param $data - array
* @param $configuration - array
* @throws \ErrorException
*/
|
d11ec8b2
Mihail
fixed permissions...
|
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
|
protected function cacheHandler( $mode, &$data = [], &$configuration = [] ){
switch ( $mode ) {
case 0:
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 {
throw new \ErrorException('Ошибка кеша');
}
break;
case 1:
Yii::$app->getCache()->set('parser_data', json_encode($data), 1800);
// сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800);
break;
default:
if( Yii::$app->getCache()->exists('parser_data') )
Yii::$app->getCache()->delete('parser_data');
if( Yii::$app->getCache()->exists('parser_configuration') )
Yii::$app->getCache()->delete('parser_configuration');
}
|
b846d5f9
Mihail
add expiration ti...
|
251
|
|
d11ec8b2
Mihail
fixed permissions...
|
252
|
}
|
058dbbcc
Mihail
change writing cr...
|
253
|
|
e323ebc1
Mihail
fixed issues with...
|
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
// protected function validateModel( BaseActiveRecord $model, array $data ){
//
// foreach ( $data as $row ) {
// // подготовим данные к валидации
// $validate_attr[$model->formName()] = $row;
// if( !$model->load( $validate_attr ) ){
// // такой ситуации не должно быть, но на всякий случай
// throw new ErrorException('Незаполнены обязательные поля формы.');
// }
// if ( !$model->validate( ) ) {
// $model->throwStringErrorException( key( $data ) );
// };
// }
//
// return true;
//
// }
|
7776ca75
Mihail
add form, model a...
|
271
|
}
|