Test Failed
Push — master ( cb83f6...869dac )
by Alexey
05:09
created

ActiveForm::checkRequest()   F

Complexity

Conditions 35
Paths 218

Size

Total Lines 102
Code Lines 77

Duplication

Lines 13
Ratio 12.75 %

Importance

Changes 0
Metric Value
cc 35
eloc 77
nc 218
nop 2
dl 13
loc 102
rs 3.8448
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Active form
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
12
namespace Ui;
13
14
class ActiveForm extends \Object {
15
16
    public $model = null;
17
    public $modelName = '';
18
    public $header = "";
19
    public $action = "";
20
    public $form = [];
21
    public $inputs = [];
22
    public $formName = 'noNameForm';
23
    public $requestFormName = '';
24
    public $requestFullFormName = '';
25
    public $parent = null;
26
27
    /**
28
     *
29
     * @param array|\Model $model
30
     * @param array|string $form
31
     */
32
    public function __construct($model, $form = '') {
33
        if (is_array($model)) {
34
            $this->form = $model;
35
            if (is_string($form)) {
36
                $this->formName = $form;
37
            }
38
        } else {
39
            $this->model = $model;
40
            $this->modelName = get_class($model);
41
            if (is_array($form)) {
42
                if (empty($form)) {
43
                    throw new \Exception('empty form');
44
                }
45
                $this->form = $form;
46
            } else {
47
                $this->formName = $form;
48
                $this->form = \App::$cur->ui->getModelForm($this->modelName, $form);
49
                if (empty($this->form)) {
50
                    throw new \Exception('empty form ' . $form);
51
                }
52
                $this->inputs = $this->getInputs();
53
            }
54
        }
55
        $this->requestFormName = "ActiveForm_{$this->formName}";
56
        $modeName = $this->modelName;
57
58
        if (!empty($this->form['name'])) {
59
            $this->header = $this->form['name'];
60
        } elseif (!empty($modeName::$objectName)) {
61
            $this->header = $modeName::$objectName;
62
        } else {
63
            $this->header = $this->modelName;
64
        }
65
    }
66
67
    public function getInputs() {
68
        $inputs = !empty($this->form['inputs']) ? $this->form['inputs'] : [];
69
        $modelName = $this->modelName;
70
        foreach ($this->form['map'] as $row) {
71
            foreach ($row as $col) {
72
                if (!$col || !empty($inputs[$col])) {
73
                    continue;
74
                }
75
                if (strpos($col, 'form:') === 0) {
76
                    $colPath = explode(':', $col);
77
                    if ($this->model->{$colPath[1]}) {
78
                        $inputs[$col] = new ActiveForm($this->model->{$colPath[1]}, $colPath[2]);
79
                    } else {
80
                        $relOptions = $modelName::getRelation($colPath[1]);
81 View Code Duplication
                        if (!isset($this->model->_params[$modelName::index()])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
                            $this->model->_params[$modelName::index()] = 0;
83
                        }
84
                        $relOptions['model']::fixPrefix($relOptions['col']);
85
                        $inputs[$col] = new ActiveForm(new $relOptions['model'](), $colPath[2]);
86
                    }
87
                    $inputs[$col]->parent = $this;
88
89
                    $inputs[$col]->parent = $this;
90
                } elseif (!empty($modelName::$cols[$col])) {
91
                    $inputs[$col] = $modelName::$cols[$col];
92
                }
93
            }
94
        }
95
        return $inputs;
96
    }
97
98
    public function checkRequest($params = [], $ajax = false) {
99 View Code Duplication
        if (!$this->checkAccess()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
            $this->drawError('you not have access to "' . $this->modelName . '" manager with name: "' . $this->formName . '"');
101
            return [];
102
        }
103
        $successId = 0;
104
        $modelName = $this->model;
105
        if (!empty($_POST[$this->requestFormName][$this->modelName]) || !empty($_FILES[$this->requestFormName]['tmp_name'][$this->modelName])) {
106
            $request = !empty($_POST[$this->requestFormName][$this->modelName]) ? $_POST[$this->requestFormName][$this->modelName] : [];
107
            if ($this->model) {
108
                if (!empty($this->form['handler']) && empty($_GET['notSave'])) {
109
110
                    $modelName::{$this->form['handler']}($request);
111
                    $text = 'Новый элемент был успешно добавлен';
112
                    \Msg::add($text, 'success');
113
                    \Msg::show();
114
                } else {
115
                    $presets = !empty($this->form['preset']) ? $this->form['preset'] : [];
116 View Code Duplication
                    if (!empty($this->form['userGroupPreset'][\Users\User::$cur->group_id])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
                        $presets = array_merge($presets, $this->form['userGroupPreset'][\Users\User::$cur->group_id]);
118
                    }
119
                    $afterSave = [];
120
                    $error = false;
121
                    foreach ($this->inputs as $col => $param) {
122
                        if (!empty($presets[$col])) {
123
                            continue;
124
                        }
125
                        if (is_object($param)) {
126
                            $afterSave[$col] = $param;
127
                            continue;
128
                        }
129 View Code Duplication
                        if (!empty($this->form['userGroupReadonly'][\Users\User::$cur->group_id]) && in_array($col, $this->form['userGroupReadonly'][\Users\User::$cur->group_id])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
                            continue;
131
                        }
132
                        $inputClassName = '\Ui\ActiveForm\Input\\' . ucfirst($param['type']);
133
                        $input = new $inputClassName();
134
                        $input->activeForm = $this;
135
                        $input->activeFormParams = $params;
136
                        $input->modelName = $this->modelName;
137
                        $input->colName = $col;
138
                        $input->colParams = $param;
139
                        try {
140
                            $input->validate($request);
141
                            $input->parseRequest($request);
142
                        } catch (\Exception $exc) {
143
                            \Msg::add($exc->getMessage(), 'danger');
144
                            $error = true;
145
                        }
146
                    }
147
                    if (!$error && empty($_GET['notSave'])) {
148
                        foreach ($presets as $col => $preset) {
149
                            if (!empty($preset['value'])) {
150
                                $this->model->$col = $preset['value'];
151
                            } elseif (!empty($preset['userCol'])) {
152
                                if (strpos($preset['userCol'], ':')) {
153
                                    $rel = substr($preset['userCol'], 0, strpos($preset['userCol'], ':'));
154
                                    $param = substr($preset['userCol'], strpos($preset['userCol'], ':') + 1);
155
                                    $this->model->$col = \Users\User::$cur->$rel->$param;
156
                                } else {
157
                                    $this->model->$col = \Users\User::$cur->{$preset['userCol']};
158
                                }
159
                            }
160
                        }
161
                        if (!$this->parent) {
162
                            if (!empty($this->form['successText'])) {
163
                                $text = $this->form['successText'];
164
                            } else {
165
                                $text = $this->model->pk() ? 'Изменения были успешно сохранены' : 'Новый элемент был успешно добавлен';
166
                            }
167
                            \Msg::add($text, 'success');
168
                        }
169
170
                        $this->model->save(!empty($params['dataManagerParams']) ? $params['dataManagerParams'] : []);
171
                        foreach ($afterSave as $col => $form) {
172
                            if (strpos($col, 'form:') === 0) {
173
                                $colPath = explode(':', $col);
174
                                if (!$this->model->{$colPath[1]}) {
175
                                    $relOptions = $modelName::getRelation($colPath[1]);
176 View Code Duplication
                                    if (!isset($this->model->_params[$modelName::index()])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
                                        $this->model->_params[$modelName::index()] = 0;
178
                                    }
179
                                    $relOptions['model']::fixPrefix($relOptions['col']);
180
                                    $form->model->{$relOptions['col']} = $this->model->_params[$modelName::index()];
181
                                }
182
                            }
183
                            $form->checkRequest();
184
                        }
185
                    if ($ajax) {
186
                        \Msg::show();
187
                    } elseif (!empty($_GET['redirectUrl'])) {
188
                        \Tools::redirect($_GET['redirectUrl'] . (!empty($_GET['dataManagerHash']) ? '#' . $_GET['dataManagerHash'] : ''));
189
                    }
190
                    $successId = $this->model->pk();
191
                }
192
            }
193
        }
194
        if (!is_array($params) && is_callable($params)) {
195
            $params($request);
196
        }
197
    }
198
return $successId;
199
}
200
201
public
202
function draw($params = [], $ajax = false) {
203 View Code Duplication
    if (!$this->checkAccess()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
204
        $this->drawError('you not have access to "' . $this->modelName . '" form with name: "' . $this->formName . '"');
205
        return [];
206
    }
207
    $form = new Form(!empty($this->form['formOptions']) ? $this->form['formOptions'] : []);
208
    \App::$cur->view->widget('Ui\ActiveForm', ['form' => $form, 'activeForm' => $this, 'ajax' => $ajax, 'params' => $params]);
209
}
210
211
public
212
function drawCol($colName, $options, $form, $params = []) {
213
    if (is_object($options)) {
214
        $options->draw();
215
    } else {
216
        $inputClassName = '\Ui\ActiveForm\Input\\' . ucfirst($options['type']);
217
        $input = new $inputClassName();
218
        $input->form = $form;
219
        $input->activeForm = $this;
220
        $input->activeFormParams = $params;
221
        $input->modelName = $this->modelName;
222
        $input->colName = $colName;
223
        $input->colParams = $options;
224
        $input->options = !empty($options['options']) ? $options['options'] : [];
225
        $input->draw();
226
    }
227
    return true;
228
}
229
230
public
231
static function getOptionsList($inputParams, $params = [], $modelName = '', $aditionalInputNamePrefix = 'aditional', $options = []) {
232
    $values = [];
233
    switch ($inputParams['source']) {
234
        case 'model':
235
            $values = $inputParams['model']::getList(['forSelect' => true]);
236
            break;
237
        case 'array':
238
            $values = $inputParams['sourceArray'];
239
            break;
240
        case 'method':
241
            if (!empty($inputParams['params'])) {
242
                $values = call_user_func_array([\App::$cur->$inputParams['module'], $inputParams['method']], $inputParams['params']);
243
            } else {
244
                $values = \App::$cur->$inputParams['module']->$inputParams['method']();
245
            }
246
            break;
247
        case 'relation':
248
            if (!$modelName) {
249
                return [];
250
            }
251
            $relation = $modelName::getRelation($inputParams['relation']);
252 View Code Duplication
            if (!empty($params['dataManagerParams']['appType'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
253
                $options['appType'] = $params['dataManagerParams']['appType'];
254
            }
255
            $items = [];
256
            if (class_exists($relation['model'])) {
257
                $filters = $relation['model']::managerFilters();
258
                if (!empty($filters['getRows']['where'])) {
259
                    $options['where'][] = $filters['getRows']['where'];
260
                }
261
                if (!empty($relation['where'])) {
262
                    $options['where'][] = $relation['where'];
263
                }
264
                if (!empty($relation['order'])) {
265
                    $options['order'] = $relation['order'];
266
                }
267
                if (!empty($inputParams['itemName'])) {
268
                    $options['itemName'] = $inputParams['itemName'];
269
                }
270
                $items = $relation['model']::getList($options);
271
            }
272
            if (!empty($params['noEmptyValue'])) {
273
                $values = [];
274
            } else {
275
                $values = [0 => 'Не задано'];
276
            }
277
            foreach ($items as $key => $item) {
278
                if (!empty($inputParams['showCol'])) {
279
                    if (is_array($inputParams['showCol'])) {
280
                        switch ($inputParams['showCol']['type']) {
281
                            case 'staticMethod':
282
                                $values[$key] = $inputParams['showCol']['class']::{$inputParams['showCol']['method']}($item);
283
                                break;
284
                        }
285
                    } else {
286
                        $values[$key] = $item->$inputParams['showCol'];
287
                    }
288
                } else {
289
                    $values[$key] = $item->name();
290
                }
291
            }
292
            break;
293
    }
294
    foreach ($values as $key => $value) {
295
        if (is_array($value) && !empty($value['input']) && empty($value['input']['noprefix'])) {
296
            $values[$key]['input']['name'] = $aditionalInputNamePrefix . "[{$value['input']['name']}]";
297
        }
298
    }
299
    return $values;
300
}
301
302
/**
303
 * Draw error message
304
 *
305
 * @param string $errorText
306
 */
307
public
308
function drawError($errorText) {
309
    echo $errorText;
310
}
311
312
/**
313
 * Check access cur user to form with name in param and $model
314
 *
315
 * @return boolean
316
 */
317
public
318
function checkAccess() {
319
    if (empty($this->form)) {
320
        $this->drawError('"' . $this->modelName . '" form with name: "' . $this->formName . '" not found');
321
        return false;
322
    }
323
    if (\App::$cur->Access && !\App::$cur->Access->checkAccess($this)) {
324
        return false;
325
    }
326
    if (!empty($this->form['options']['access']['apps']) && !in_array(\App::$cur->name, $this->form['options']['access']['apps'])) {
327
        return false;
328
    }
329 View Code Duplication
    if (!empty($this->form['options']['access']['groups']) && in_array(\Users\User::$cur->group_id, $this->form['options']['access']['groups'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
330
        return true;
331
    }
332
    if ($this->model && !empty($this->form['options']['access']['self']) && \Users\User::$cur->id == $this->model->user_id) {
333
        return true;
334
    }
335
    if ($this->formName == 'manager' && !\Users\User::$cur->isAdmin()) {
336
        return false;
337
    }
338
    return true;
339
}
340
341
}
342