Passed
Push — v5 ( e348bf...8a8f01 )
by Alexey
06:35
created

DataManagerController::loadRowsAction()   F

Complexity

Conditions 17
Paths 300

Size

Total Lines 78
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 56
nc 300
nop 0
dl 0
loc 78
rs 3.8929
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
 * 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
class DataManagerController extends Controller {
0 ignored issues
show
Bug introduced by
The type Controller 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...
12
13
    public function parseRequest() {
14
        $return = [];
15
        $return['params'] = UserRequest::get('params', 'array', []);
0 ignored issues
show
Bug introduced by
The type UserRequest 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...
16
17
        $item = UserRequest::get('modelName', 'string', '');
18
        if (!$item) {
19
            $item = UserRequest::get('item', 'string', '');
20
        }
21
22
        if (strpos($item, ':')) {
23
            $raw = explode(':', $item);
24
            $return['modelName'] = $raw[0];
25
            $return['model'] = $return['modelName']::get($raw[1], $return['modelName']::index(), $return['params']);
26
        } else {
27
            $return['modelName'] = $item;
28
            $return['model'] = null;
29
        }
30
31
        if (!empty($return['params']['relation'])) {
32
            $relation = $return['modelName']::getRelation($return['params']['relation']);
33
            if (!empty($relation['type']) && $relation['type'] == 'relModel') {
34
                $return['modelName'] = $relation['relModel'];
35
            } else {
36
                $return['modelName'] = $relation['model'];
37
            }
38
        }
39
        $return['params']['filters'] = UserRequest::get('filters', 'array', []);
40
        $return['params']['sortered'] = UserRequest::get('sortered', 'array', []);
41
        $return['params']['mode'] = UserRequest::get('mode', 'string', '');
42
        $return['params']['all'] = UserRequest::get('all', 'bool', false);
43
44
        $return['key'] = UserRequest::get('key', 'int', 0);
45
        $return['col'] = UserRequest::get('col', 'string', '');
46
        $return['col_value'] = UserRequest::get('col_value', 'string', '');
47
48
        $return['action'] = UserRequest::get('action', 'string', '');
49
        $return['ids'] = trim(UserRequest::get('ids', 'string', ''), ',');
50
        $return['adInfo'] = UserRequest::get('adInfo', 'array', []);
51
52
        $return['download'] = UserRequest::get('download', 'bool', false);
53
        $return['silence'] = UserRequest::get('silence', 'bool', false);
54
55
        $return['managerName'] = UserRequest::get('managerName', 'string', 'manager');
56
        if (!empty($return['params']['managerName'])) {
57
            $return['managerName'] = $return['params']['managerName'];
58
        }
59
        if (!$return['managerName']) {
60
            $return['managerName'] = 'manager';
61
        }
62
63
        return $return;
64
    }
65
66
    public function indexAction() {
67
        $result = new Server\Result();
68
69
        ob_start();
70
71
        $request = $this->parseRequest();
72
73
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
74
        $dataManager->draw($request['params'], $request['model']);
75
76
        $result->content = ob_get_contents();
77
78
        ob_end_clean();
79
80
        $result->send();
81
    }
82
83
    public function loadRowsAction() {
84
        $result = new Server\Result();
85
        $result->content = [];
86
87
        ob_start();
88
89
        $request = $this->parseRequest();
90
91
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
92
        if ($request['download']) {
93
94
            ini_set('memory_limit', '4000M');
95
            set_time_limit(0);
96
97
            $request['params']['all'] = true;
98
            $request['params']['download'] = true;
99
            ob_end_clean();
100
            header('Content-Encoding: UTF-8');
101
            header("Content-Type: text/csv");
102
            header("Content-Disposition: attachment; filename=" . str_replace(' ', '_', $request['modelName']::$objectName ? $request['modelName']::$objectName : $request['modelName']) . ".csv");
103
            echo "\xEF\xBB\xBF"; // UTF-8 BOM
104
105
106
            $cols = $dataManager->getCols();
107
            if ($dataManager->getActions(true)) {
108
                $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

108
                $cols = array_slice(/** @scrutinizer ignore-type */ $cols, 1);
Loading history...
109
            }
110
            $endRow = true;
111
            foreach ($cols as $colName => $options) {
112
                if (!$endRow) {
113
                    echo ";";
114
                }
115
                $endRow = false;
116
                echo '"' . $options['label'] . '"';
117
            }
118
            echo "\n";
119
            $endRow = true;
120
        }
121
        if (!$request['params']['all']) {
122
            $pages = $dataManager->getPages($request['params'], $request['model']);
123
            $request['params']['page'] = !empty($pages->params['page']) ? $pages->params['page'] : $dataManager->page;
124
            $request['params']['limit'] = !empty($pages->params['limit']) ? $pages->params['limit'] : $dataManager->limit;
125
        }
126
        $rows = $dataManager->getRows($request['params'], $request['model']);
127
        foreach ($rows as $row) {
128
            if ($request['download']) {
129
                foreach ($row as $col) {
130
                    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...
131
                        echo ";";
132
                    }
133
                    $endRow = false;
134
                    echo '"' . str_replace(["\n", '"'], ['“'], $col) . '"';
135
                }
136
                echo "\n";
137
                $endRow = true;
138
            } else {
139
                Ui\Table::drawRow($row);
140
            }
141
        }
142
        if ($request['download']) {
143
            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...
144
        }
145
146
        $result->content['rows'] = ob_get_contents();
147
        $result->content['summary'] =  $dataManager->getSummary($request['params'], $request['model']);
148
        ob_clean();
149
150
        $result->content['pages'] = '';
151
        if (isset($pages) && $pages) {
152
            if ($pages) {
153
                $pages->draw();
154
                echo '<div style="background:#fff;">записей: <b>' . $pages->options['count'] . '</b>. страница <b>' . $pages->params['page'] . '</b> из <b>' . $pages->params['pages'] . '</b></div>';
155
            }
156
            $result->content['pages'] = ob_get_contents();
157
            ob_end_clean();
158
        }
159
        $result->send();
160
    }
161
162
    public function loadCategorysAction() {
163
        $result = new Server\Result();
164
165
        ob_start();
166
167
        $request = $this->parseRequest();
168
169
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
170
        $dataManager->drawCategorys();
171
172
        $result->content = ob_get_contents();
173
        ob_end_clean();
174
175
        $result->send();
176
    }
177
178
    public function delRowAction() {
179
180
        $request = $this->parseRequest();
181
182
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
183
184
        if ($dataManager->checkAccess()) {
185
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
186
            if ($model) {
187
                $model->delete($request['params']);
188
            }
189
        }
190
        $result = new Server\Result();
191
        $result->successMsg = empty($request['silence']) ? 'Запись удалена' : '';
192
        $result->send();
193
    }
194
195
    public function updateRowAction() {
196
197
        $request = $this->parseRequest();
198
199
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
200
201
        if ($dataManager->checkAccess()) {
202
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
203
            if ($model) {
204
                $model->{$request['col']} = $request['col_value'];
205
                $model->save($request['params']);
206
            }
207
        }
208
        $result = new Server\Result();
209
        $result->successMsg = empty($request['silence']) ? 'Запись Обновлена' : '';
210
        $result->send();
211
    }
212
213
    public function groupActionAction() {
214
        $request = $this->parseRequest();
215
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
216
        $result = new Server\Result();
217
        $result->success = false;
218
        $result->content = 'Не удалось выполнить операцию';
219
        if ($dataManager->checkAccess()) {
220
            $ids = trim($request['ids'], ' ,');
221
            if ($request['action'] && $ids) {
222
                $actions = $dataManager->getActions();
223
                if (!empty($actions[$request['action']])) {
224
                    $actionParams = $actions[$request['action']];
225
                    if (!empty($actionParams['access']['groups']) && !in_array(\Users\User::$cur->group_id, $actionParams['access']['groups'])) {
226
                        $result->content = 'У вас нет прав доступа к операции ' . (!isset($actionParams['name']) ? $actionParams['className']::$name : $actionParams['name']);
227
                    } else {
228
                        try {
229
                            $result->successMsg = $actionParams['className']::groupAction($dataManager, $ids, $actionParams, !empty($_GET['adInfo']) ? $_GET['adInfo'] : []);
230
                            $result->success = true;
231
                        } catch (\Exception $e) {
232
                            $result->content = $e->getMessage();
233
                        }
234
                    }
235
                }
236
            }
237
        } else {
238
            $result->content = 'У вас нет прав доступа к менеджеру ' . $request['managerName'] . ' модели ' . $request['modelName'];
239
        }
240
        $result->send();
241
    }
242
243
    public function delCategoryAction() {
244
245
        $request = $this->parseRequest();
246
247
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
248
249
        if ($dataManager->checkAccess() && !empty($dataManager->managerOptions['categorys'])) {
250
            $categoryModel = $dataManager->managerOptions['categorys']['model'];
251
            $model = $categoryModel::get($request['key'], $categoryModel::index(), $request['params']);
252
            if ($model) {
253
                $model->delete($request['params']);
254
            }
255
        }
256
        $result = new Server\Result();
257
        $result->send();
258
    }
259
}