Completed
Push — master ( f81666...55a9f3 )
by Alexey
05:42
created

DataManagerController   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 243
Duplicated Lines 13.99 %

Coupling/Cohesion

Components 1
Dependencies 5
Metric Value
wmc 40
lcom 1
cbo 5
dl 34
loc 243
rs 8.2608

8 Methods

Rating   Name   Duplication   Size   Complexity  
C parseRequest() 0 50 7
A indexAction() 0 17 1
C loadRowsAction() 0 70 13
A loadCategorysAction() 0 16 1
A delRowAction() 17 17 4
A updateRowAction() 0 18 4
B groupActionAction() 0 27 6
A delCategoryAction() 17 17 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DataManagerController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DataManagerController, and based on these observations, apply Extract Interface, too.

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
12
{
13
    public function parseRequest()
14
    {
15
        $return = [];
16
        $return['params'] = UserRequest::get('params', 'array', []);
17
18
        $item = UserRequest::get('modelName', 'string', '');
19
        if (!$item) {
20
            $item = UserRequest::get('item', 'string', '');
21
        }
22
23
        if (strpos($item, ':')) {
24
            $raw = explode(':', $item);
25
            $return['modelName'] = $raw[0];
26
            $return['model'] = $return['modelName']::get($raw[1], $return['modelName']::index(), $return['params']);
27
        } else {
28
            $return['modelName'] = $item;
29
            $return['model'] = null;
30
        }
31
32
        if (!empty($return['params']['relation'])) {
33
            $relation = $return['modelName']::getRelation($return['params']['relation']);
34
            if (!empty($relation['type']) && $relation['type'] == 'relModel') {
35
                $return['modelName'] = $relation['relModel'];
36
            } else {
37
                $return['modelName'] = $relation['model'];
38
            }
39
        }
40
        $return['params']['filters'] = UserRequest::get('filters', 'array', []);
41
        $return['params']['sortered'] = UserRequest::get('sortered', 'array', []);
42
        $return['params']['mode'] = UserRequest::get('mode', 'string', '');
43
        $return['params']['all'] = UserRequest::get('all', 'bool', false);
44
45
        $return['key'] = UserRequest::get('key', 'int', 0);
46
        $return['col'] = UserRequest::get('col', 'string', '');
47
        $return['col_value'] = UserRequest::get('col_value', 'string', '');
48
49
        $return['action'] = UserRequest::get('action', 'string', '');
50
        $return['ids'] = trim(UserRequest::get('ids', 'string', ''), ',');
51
        $return['adInfo'] = UserRequest::get('adInfo', 'array', []);
52
53
        $return['download'] = UserRequest::get('download', 'bool', false);
54
        $return['silence'] = UserRequest::get('silence', 'bool', false);
55
56
        $return['managerName'] = UserRequest::get('managerName', 'string', 'manager');
57
        if (!$return['managerName']) {
58
            $return['managerName'] = 'manager';
59
        }
60
61
        return $return;
62
    }
63
64
    public function indexAction()
65
    {
66
        $result = new Server\Result();
67
68
        ob_start();
69
70
        $request = $this->parseRequest();
71
72
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
73
        $dataManager->draw($request['params'], $request['model']);
74
75
        $result->content = ob_get_contents();
76
77
        ob_end_clean();
78
79
        $result->send();
80
    }
81
82
    public function loadRowsAction()
83
    {
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
            $request['params']['all'] = true;
94
            $request['params']['download'] = true;
95
            set_time_limit(0);
96
            ob_end_clean();
97
            header('Content-Encoding: UTF-8');
98
            header("Content-Type: text/csv");
99
            header("Content-Disposition: attachment; filename=" . $request['modelName']::$objectName . '.csv');
100
            echo "\xEF\xBB\xBF"; // UTF-8 BOM
101
102
103
            $cols = $dataManager->getCols();
104
            $cols = array_slice($cols, (!empty($dataManager->managerOptions['groupActions']) ? 1 : 0));
105
            $endRow = true;
106
            foreach ($cols as $colName => $options) {
107
                if (!$endRow) {
108
                    echo ";";
109
                }
110
                $endRow = false;
111
                echo '"' . $options['label'] . '"';
112
            }
113
            echo "\n";
114
            $endRow = true;
115
        }
116
        $rows = $dataManager->getRows($request['params'], $request['model']);
117
        foreach ($rows as $row) {
118
            if ($request['download']) {
119
                $row = array_slice($row, (!empty($dataManager->managerOptions['groupActions']) ? 1 : 0), -1);
120
                foreach ($row as $col) {
121
                    if (!$endRow) {
122
                        echo ";";
123
                    }
124
                    $endRow = false;
125
                    echo '"' . str_replace("\n", '', $col) . '"';
126
                }
127
                echo "\n";
128
                $endRow = true;
129
            } else {
130
                Ui\Table::drawRow($row);
131
            }
132
        }
133
        if ($request['download']) {
134
            exit();
135
        }
136
137
        $result->content['rows'] = ob_get_contents();
138
        ob_clean();
139
140
        $result->content['pages'] = '';
141
142
        if (!$request['params']['all']) {
143
            $pages = $dataManager->getPages($request['params'], $request['model']);
144
            if ($pages) {
145
                $pages->draw();
146
            }
147
            $result->content['pages'] = ob_get_contents();
148
            ob_end_clean();
149
        }
150
        $result->send();
151
    }
152
153
    public function loadCategorysAction()
154
    {
155
        $result = new Server\Result();
156
157
        ob_start();
158
159
        $request = $this->parseRequest();
160
161
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
162
        $dataManager->drawCategorys();
163
164
        $result->content = ob_get_contents();
165
        ob_end_clean();
166
167
        $result->send();
168
    }
169
170 View Code Duplication
    public function delRowAction()
171
    {
172
173
        $request = $this->parseRequest();
174
175
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
176
177
        if ($dataManager->checkAccess()) {
178
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
179
            if ($model) {
180
                $model->delete($request['params']);
181
            }
182
        }
183
        $result = new Server\Result();
184
        $result->successMsg = empty($request['silence']) ? 'Запись удалена' : '';
185
        $result->send();
186
    }
187
188
    public function updateRowAction()
189
    {
190
191
        $request = $this->parseRequest();
192
193
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
194
195
        if ($dataManager->checkAccess()) {
196
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
197
            if ($model) {
198
                $model->{$request['col']} = $request['col_value'];
199
                $model->save($request['params']);
200
            }
201
        }
202
        $result = new Server\Result();
203
        $result->successMsg = empty($request['silence']) ? 'Запись Обновлена' : '';
204
        $result->send();
205
    }
206
207
    public function groupActionAction()
208
    {
209
        $request = $this->parseRequest();
210
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
211
        $result = new Server\Result();
212
        $result->success = false;
213
        $result->content = 'Не удалось выполнить операцию';
214
        if ($dataManager->checkAccess()) {
215
            $ids = trim($request['ids'], ' ,');
216
            if ($request['action'] && $ids) {
217
218
                $actions = $dataManager->getActions();
219
                if (!empty($actions[$request['action']])) {
220
                    $actionParams = $actions[$request['action']];
221
                    try {
222
                        $result->successMsg = $actionParams['className']::groupAction($dataManager, $ids, $actionParams);
223
                        $result->success = true;
224
                    } catch (\Exception $e) {
225
                        $result->content = $e->getMessage();
226
                    }
227
                }
228
            }
229
        } else {
230
            $result->content = 'У вас нет прав доступа к менеджеру ' . $request['managerName'] . ' модели ' . $request['modelName'];
231
        }
232
        $result->send();
233
    }
234
235 View Code Duplication
    public function delCategoryAction()
236
    {
237
238
        $request = $this->parseRequest();
239
240
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
241
242
        if ($dataManager->checkAccess() && !empty($dataManager->managerOptions['categorys'])) {
243
            $categoryModel = $dataManager->managerOptions['categorys']['model'];
244
            $model = $categoryModel::get($request['key'], $categoryModel::index(), $request['params']);
245
            if ($model) {
246
                $model->delete($request['params']);
247
            }
248
        }
249
        $result = new Server\Result();
250
        $result->send();
251
    }
252
253
}
254