Passed
Push — v5 ( 6adbf6...c0775f )
by Alexey
06:03
created

DataManagerController::loadRowsAction()   D

Complexity

Conditions 17
Paths 225

Size

Total Lines 79
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 55
nc 225
nop 0
dl 0
loc 79
rs 4.3005
c 1
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
 * Data manager controller
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 Inji\Ui;
13
14
use Inji\Controller;
15
use Inji\Server\Result;
16
use Inji\UserRequest;
17
18
class DataManagerController extends Controller {
19
20
    public function parseRequest() {
21
        $return = [];
22
        $return['params'] = UserRequest::get('params', 'array', []);
23
24
        $item = UserRequest::get('modelName', 'string', '');
25
        if (!$item) {
26
            $item = UserRequest::get('item', 'string', '');
27
        }
28
29
        if (strpos($item, ':')) {
30
            $raw = explode(':', $item);
31
            $return['modelName'] = $raw[0];
32
            $return['model'] = $return['modelName']::get($raw[1], $return['modelName']::index(), $return['params']);
33
        } else {
34
            $return['modelName'] = $item;
35
            $return['model'] = null;
36
        }
37
38
        if (!empty($return['params']['relation'])) {
39
            $relation = $return['modelName']::getRelation($return['params']['relation']);
40
            if (!empty($relation['type']) && $relation['type'] == 'relModel') {
41
                $return['modelName'] = $relation['relModel'];
42
            } else {
43
                $return['modelName'] = $relation['model'];
44
            }
45
        }
46
        $return['params']['filters'] = UserRequest::get('filters', 'array', []);
47
        $return['params']['sortered'] = UserRequest::get('sortered', 'array', []);
48
        $return['params']['mode'] = UserRequest::get('mode', 'string', '');
49
        $return['params']['all'] = UserRequest::get('all', 'bool', false);
50
51
        $return['key'] = UserRequest::get('key', 'int', 0);
52
        $return['col'] = UserRequest::get('col', 'string', '');
53
        $return['col_value'] = UserRequest::get('col_value', 'string', '');
54
55
        $return['action'] = UserRequest::get('action', 'string', '');
56
        $return['ids'] = trim(UserRequest::get('ids', 'string', ''), ',');
57
        $return['adInfo'] = UserRequest::get('adInfo', 'array', []);
58
59
        $return['download'] = UserRequest::get('download', 'bool', false);
60
        $return['silence'] = UserRequest::get('silence', 'bool', false);
61
62
        $return['managerName'] = UserRequest::get('managerName', 'string', 'manager');
63
        if (!empty($return['params']['managerName'])) {
64
            $return['managerName'] = $return['params']['managerName'];
65
        }
66
        if (!$return['managerName']) {
67
            $return['managerName'] = 'manager';
68
        }
69
70
        return $return;
71
    }
72
73
    public function indexAction() {
74
        $result = new Result();
75
76
        ob_start();
77
78
        $request = $this->parseRequest();
79
80
        $dataManager = new DataManager($request['modelName'], $request['managerName']);
0 ignored issues
show
Unused Code introduced by
The call to Inji\Ui\DataManager::__construct() has too many arguments starting with $request['managerName']. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
        $dataManager = /** @scrutinizer ignore-call */ new DataManager($request['modelName'], $request['managerName']);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
81
        $dataManager->draw($request['params'], $request['model']);
82
83
        $result->content = ob_get_contents();
84
85
        ob_end_clean();
86
87
        $result->send();
88
    }
89
90
    public function loadRowsAction() {
91
        $result = new Result();
92
        $result->content = [];
93
94
        ob_start();
95
96
        $request = $this->parseRequest();
97
98
        $dataManager = DataManager::forModel($request['modelName'], $request['managerName']);
99
100
101
        if ($request['download']) {
102
103
            ini_set('memory_limit', '4000M');
104
            set_time_limit(0);
105
106
            $request['params']['all'] = true;
107
            $request['params']['download'] = true;
108
            ob_end_clean();
109
            header('Content-Encoding: UTF-8');
110
            header("Content-Type: text/csv");
111
            header("Content-Disposition: attachment; filename=" . str_replace(' ', '_', $request['modelName']::$objectName ? $request['modelName']::$objectName : $request['modelName']) . ".csv");
112
            echo "\xEF\xBB\xBF"; // UTF-8 BOM
113
114
115
            $cols = $dataManager->getCols();
116
            if ($dataManager->getActions(true)) {
117
                $cols = array_slice($cols, 1);
0 ignored issues
show
Bug introduced by
$cols of type string is incompatible with the type array expected by parameter $array of array_slice(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
                $cols = array_slice(/** @scrutinizer ignore-type */ $cols, 1);
Loading history...
118
            }
119
            $endRow = true;
120
            foreach ($cols as $colName => $options) {
121
                if (!$endRow) {
122
                    echo ";";
123
                }
124
                $endRow = false;
125
                echo '"' . $options['label'] . '"';
126
            }
127
            echo "\n";
128
            $endRow = true;
129
        }
130
        if (!$request['params']['all']) {
131
            $pages = $dataManager->getPages($request['params'], $request['model']);
132
            $request['params']['page'] = !empty($pages->params['page']) ? $pages->params['page'] : $dataManager->page;
133
            $request['params']['limit'] = !empty($pages->params['limit']) ? $pages->params['limit'] : $dataManager->limit;
134
        }
135
        $rows = $dataManager->getRows($request['params'], $request['model']);
136
        foreach ($rows as $row) {
137
            if ($request['download']) {
138
                foreach ($row as $col) {
139
                    if (!$endRow) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $endRow does not seem to be defined for all execution paths leading up to this point.
Loading history...
140
                        echo ";";
141
                    }
142
                    $endRow = false;
143
                    echo '"' . str_replace(["\n", '"'], ['“'], $col) . '"';
144
                }
145
                echo "\n";
146
                $endRow = true;
147
            } else {
148
                Table::drawRow($row);
149
            }
150
        }
151
        if ($request['download']) {
152
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
153
        }
154
155
        $result->content['rows'] = ob_get_contents();
156
        $result->content['summary'] = $dataManager->getSummary($request['params'], $request['model']);
157
        ob_clean();
158
159
        $result->content['pages'] = '';
160
        if (isset($pages) && $pages) {
161
            if ($pages) {
162
                $pages->draw();
163
                echo '<div style="background:#fff;">записей: <b>' . $pages->options['count'] . '</b>. страница <b>' . $pages->params['page'] . '</b> из <b>' . $pages->params['pages'] . '</b></div>';
164
            }
165
            $result->content['pages'] = ob_get_contents();
166
            ob_end_clean();
167
        }
168
        $result->send();
169
    }
170
171
    public function loadCategorysAction() {
172
        $result = new Server\Result();
0 ignored issues
show
Bug introduced by
The type Inji\Ui\Server\Result was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
173
174
        ob_start();
175
176
        $request = $this->parseRequest();
177
178
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
0 ignored issues
show
Bug introduced by
The type Inji\Ui\Ui\DataManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
179
        $dataManager->drawCategorys();
180
181
        $result->content = ob_get_contents();
182
        ob_end_clean();
183
184
        $result->send();
185
    }
186
187
    public function delRowAction() {
188
189
        $request = $this->parseRequest();
190
        $dataManager = DataManager::forModel($request['modelName'], $request['managerName']);
191
        if ($dataManager->checkAccess()) {
192
            $builder = $dataManager->modelBuilderFromParams();
193
            $builder->where($dataManager->modelName::index());
194
            $model = $builder->get();
195
            if ($model) {
196
                $model->delete();
197
            }
198
        }
199
        $result = new Result();
200
        $result->successMsg = empty($request['silence']) ? 'Запись удалена' : '';
201
        $result->send();
202
    }
203
204
    public function updateRowAction() {
205
206
        $request = $this->parseRequest();
207
208
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
209
210
        if ($dataManager->checkAccess()) {
211
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
212
            if ($model) {
213
                $model->{$request['col']} = $request['col_value'];
214
                $model->save($request['params']);
215
            }
216
        }
217
        $result = new Server\Result();
218
        $result->successMsg = empty($request['silence']) ? 'Запись Обновлена' : '';
219
        $result->send();
220
    }
221
222
    public function groupActionAction() {
223
        $request = $this->parseRequest();
224
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
225
        $result = new Server\Result();
226
        $result->success = false;
227
        $result->content = 'Не удалось выполнить операцию';
228
        if ($dataManager->checkAccess()) {
229
            $ids = trim($request['ids'], ' ,');
230
            if ($request['action'] && $ids) {
231
                $actions = $dataManager->getActions();
232
                if (!empty($actions[$request['action']])) {
233
                    $actionParams = $actions[$request['action']];
234
                    if (!empty($actionParams['access']['groups']) && !in_array(\Users\User::$cur->group_id, $actionParams['access']['groups'])) {
235
                        $result->content = 'У вас нет прав доступа к операции ' . (!isset($actionParams['name']) ? $actionParams['className']::$name : $actionParams['name']);
236
                    } else {
237
                        try {
238
                            $result->successMsg = $actionParams['className']::groupAction($dataManager, $ids, $actionParams, !empty($_GET['adInfo']) ? $_GET['adInfo'] : []);
239
                            $result->success = true;
240
                        } catch (\Exception $e) {
241
                            $result->content = $e->getMessage();
242
                        }
243
                    }
244
                }
245
            }
246
        } else {
247
            $result->content = 'У вас нет прав доступа к менеджеру ' . $request['managerName'] . ' модели ' . $request['modelName'];
248
        }
249
        $result->send();
250
    }
251
252
    public function delCategoryAction() {
253
254
        $request = $this->parseRequest();
255
256
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
257
258
        if ($dataManager->checkAccess() && !empty($dataManager->managerOptions['categorys'])) {
259
            $categoryModel = $dataManager->managerOptions['categorys']['model'];
260
            $model = $categoryModel::get($request['key'], $categoryModel::index(), $request['params']);
261
            if ($model) {
262
                $model->delete($request['params']);
263
            }
264
        }
265
        $result = new Server\Result();
266
        $result->send();
267
    }
268
}