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;
|
d11ec8b2
Mihail
fixed permissions...
|
15
|
use yii\base\Model;
|
22fcf59f
Mihail
add form result f...
|
16
|
use yii\data\ArrayDataProvider;
|
d11ec8b2
Mihail
fixed permissions...
|
17
|
use yii\db\ActiveRecord;
|
a8808843
Administrator
access in admin
|
18
|
use yii\filters\VerbFilter;
|
7776ca75
Mihail
add form, model a...
|
19
20
21
|
use yii\filters\AccessControl;
use backend\models\UploadFileCrossingForm;
use backend\models\DetailsCrosses;
|
22fcf59f
Mihail
add form result f...
|
22
|
use yii\multiparser\DynamicFormHelper;
|
7776ca75
Mihail
add form, model a...
|
23
24
25
26
27
28
29
|
use yii\web\UploadedFile;
use \Yii;
class CrossingUploadController extends BaseController
{
public $layout = "/column";
|
a8808843
Administrator
access in admin
|
30
|
|
058dbbcc
Mihail
change writing cr...
|
31
32
33
34
|
/**
* @inheritdoc
*/
public function behaviors()
|
7776ca75
Mihail
add form, model a...
|
35
36
37
38
39
40
|
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
|
058dbbcc
Mihail
change writing cr...
|
41
|
'actions' => ['result', 'index', 'write'],
|
7776ca75
Mihail
add form, model a...
|
42
43
44
45
46
|
'allow' => true,
'roles' => ['@'],
],
],
],
|
a8808843
Administrator
access in admin
|
47
48
49
50
51
52
|
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
|
7776ca75
Mihail
add form, model a...
|
53
54
|
];
}
|
058dbbcc
Mihail
change writing cr...
|
55
|
|
7776ca75
Mihail
add form, model a...
|
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
/**
* @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...
|
81
82
83
|
if ($model->validate()) {
$file_name = $model->file->name;
$model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name;
|
7776ca75
Mihail
add form, model a...
|
84
85
|
$model->file->saveAs($model->file_path);
//запускаем парсинг
|
22fcf59f
Mihail
add form result f...
|
86
87
|
$data = $model->readFile();
// сохраняем в кеш отпарсенные даные
|
d11ec8b2
Mihail
fixed permissions...
|
88
|
$this->cacheHandler( 1, $data, $model );
|
22fcf59f
Mihail
add form result f...
|
89
|
} else if (Yii::$app->getCache()->get('parser_data')) {
|
22fcf59f
Mihail
add form result f...
|
90
|
$data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
|
22fcf59f
Mihail
add form result f...
|
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
}
$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...
|
116
117
118
119
120
121
122
123
|
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...
|
124
|
$model->addRule($key, 'in', [ 'range' => array_keys( $this->getBasicColumns() ) ]);
|
22fcf59f
Mihail
add form result f...
|
125
126
127
128
129
130
131
132
133
|
}
// провалидируем выбранные колонки
if ($model->validate()) {
// валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
$arr = $model->toArray();
// получим данные из кеша
|
d11ec8b2
Mihail
fixed permissions...
|
134
|
$this->cacheHandler( 0, $data, $configuration );
|
22fcf59f
Mihail
add form result f...
|
135
136
137
138
139
|
// соотнесем отпарсенные данные с соответствием полученным от пользователя
// для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
$data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_');
|
058dbbcc
Mihail
change writing cr...
|
140
141
|
// запустим конвертер над над данными
$data = $this->convertDataByConfiguration( $data, $configuration );
|
22fcf59f
Mihail
add form result f...
|
142
|
|
058dbbcc
Mihail
change writing cr...
|
143
|
$crosses_model = new DetailsCrosses();
|
22fcf59f
Mihail
add form result f...
|
144
|
|
d11ec8b2
Mihail
fixed permissions...
|
145
146
147
148
149
150
151
152
153
154
155
156
|
if ( $this->validateModel( $crosses_model , $data ) && $crosses_model->ManualInsertWithIgnore( $data ) ) {
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...
|
157
|
|
7776ca75
Mihail
add form, model a...
|
158
|
|
058dbbcc
Mihail
change writing cr...
|
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
} else {
// не прошла валидация форма загрузки файлов
$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...
|
176
|
}
|
22fcf59f
Mihail
add form result f...
|
177
|
|
7776ca75
Mihail
add form, model a...
|
178
|
}
|
b846d5f9
Mihail
add expiration ti...
|
179
|
|
058dbbcc
Mihail
change writing cr...
|
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
|
protected function convertDataByConfiguration( $data, $configuration ){
// доп. опции для парсера - удаление префикса в артикулах
$options['mode'] = 'crosses';
$fields = [];
if ($configuration['delete_prefix1']) {
$fields[] = 'ARTICLE';
}
if ($configuration['delete_prefix2']) {
$fields[] = 'CROSS_ARTICLE';
}
if ($fields) {
$options ['configuration'] = ["article" => $fields,
"string" => ['ARTICLE', 'CROSS_ARTICLE'],];
} else {
$options ['configuration'] = ["string" => ['ARTICLE', 'CROSS_ARTICLE'],];
}
|
d11ec8b2
Mihail
fixed permissions...
|
198
199
|
foreach ( $data as &$row ) {
$row = Yii::$app->converter->convertByConfiguration( $row, $options );
|
058dbbcc
Mihail
change writing cr...
|
200
201
202
203
204
205
206
|
}
return $data;
}
/**
|
d11ec8b2
Mihail
fixed permissions...
|
207
|
* @param $mode - int: 0 - fetch from cache, - 1 - put in cache, <2 - delete from cache
|
058dbbcc
Mihail
change writing cr...
|
208
209
210
211
|
* @param $data - array
* @param $configuration - array
* @throws \ErrorException
*/
|
d11ec8b2
Mihail
fixed permissions...
|
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
|
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...
|
236
|
|
d11ec8b2
Mihail
fixed permissions...
|
237
|
}
|
058dbbcc
Mihail
change writing cr...
|
238
|
|
d11ec8b2
Mihail
fixed permissions...
|
239
|
protected function validateModel( BaseActiveRecord $model, array $data ){
|
058dbbcc
Mihail
change writing cr...
|
240
|
|
d11ec8b2
Mihail
fixed permissions...
|
241
242
243
244
|
foreach ( $data as $row ) {
if ( !$model->validate( $row ) ) {
$model->throwStringErrorException( key( $data ) );
};
|
22fcf59f
Mihail
add form result f...
|
245
246
|
}
|
d11ec8b2
Mihail
fixed permissions...
|
247
|
return true;
|
058dbbcc
Mihail
change writing cr...
|
248
|
|
22fcf59f
Mihail
add form result f...
|
249
|
}
|
7776ca75
Mihail
add form, model a...
|
250
|
}
|