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