Completed
Push — master ( 6b7664...8cf912 )
by Alexey
05:42
created

DataManagerController   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 247
Duplicated Lines 13.77 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 11
Bugs 7 Features 0
Metric Value
c 11
b 7
f 0
dl 34
loc 247
rs 8.3396
wmc 44
lcom 1
cbo 6

8 Methods

Rating   Name   Duplication   Size   Complexity  
C parseRequest() 0 50 7
A indexAction() 0 17 1
C loadRowsAction() 0 71 13
A loadCategorysAction() 0 16 1
A delRowAction() 17 17 4
A updateRowAction() 0 18 4
D groupActionAction() 0 30 10
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
                echo '<div style="background:#fff;">записей: <b>' . $pages->options['count'] . '</b>. страница <b>' . $pages->params['page'] . '</b> из <b>' . $pages->params['pages'] . '</b></div>';
147
            }
148
            $result->content['pages'] = ob_get_contents();
149
            ob_end_clean();
150
        }
151
        $result->send();
152
    }
153
154
    public function loadCategorysAction()
155
    {
156
        $result = new Server\Result();
157
158
        ob_start();
159
160
        $request = $this->parseRequest();
161
162
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
163
        $dataManager->drawCategorys();
164
165
        $result->content = ob_get_contents();
166
        ob_end_clean();
167
168
        $result->send();
169
    }
170
171 View Code Duplication
    public function delRowAction()
172
    {
173
174
        $request = $this->parseRequest();
175
176
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
177
178
        if ($dataManager->checkAccess()) {
179
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
180
            if ($model) {
181
                $model->delete($request['params']);
182
            }
183
        }
184
        $result = new Server\Result();
185
        $result->successMsg = empty($request['silence']) ? 'Запись удалена' : '';
186
        $result->send();
187
    }
188
189
    public function updateRowAction()
190
    {
191
192
        $request = $this->parseRequest();
193
194
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
195
196
        if ($dataManager->checkAccess()) {
197
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
198
            if ($model) {
199
                $model->{$request['col']} = $request['col_value'];
200
                $model->save($request['params']);
201
            }
202
        }
203
        $result = new Server\Result();
204
        $result->successMsg = empty($request['silence']) ? 'Запись Обновлена' : '';
205
        $result->send();
206
    }
207
208
    public function groupActionAction()
1 ignored issue
show
Coding Style introduced by
groupActionAction uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
209
    {
210
        $request = $this->parseRequest();
211
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
212
        $result = new Server\Result();
213
        $result->success = false;
214
        $result->content = 'Не удалось выполнить операцию';
215
        if ($dataManager->checkAccess()) {
216
            $ids = trim($request['ids'], ' ,');
217
            if ($request['action'] && $ids) {
218
                $actions = $dataManager->getActions();
219
                if (!empty($actions[$request['action']])) {
220
                    $actionParams = $actions[$request['action']];
221
                    if (!empty($actionParams['access']['groups']) && !in_array(\Users\User::$cur->group_id, $actionParams['access']['groups'])) {
222
                        $result->content = 'У вас нет прав доступа к операции ' . (!isset($actionParams['name']) ? $actionParams['className']::$name : $actionParams['name']);
223
                    } else {
224
                        try {
225
                            $result->successMsg = $actionParams['className']::groupAction($dataManager, $ids, $actionParams, !empty($_GET['adInfo']) ? $_GET['adInfo'] : []);
226
                            $result->success = true;
227
                        } catch (\Exception $e) {
228
                            $result->content = $e->getMessage();
229
                        }
230
                    }
231
                }
232
            }
233
        } else {
234
            $result->content = 'У вас нет прав доступа к менеджеру ' . $request['managerName'] . ' модели ' . $request['modelName'];
235
        }
236
        $result->send();
237
    }
238
239 View Code Duplication
    public function delCategoryAction()
240
    {
241
242
        $request = $this->parseRequest();
243
244
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
245
246
        if ($dataManager->checkAccess() && !empty($dataManager->managerOptions['categorys'])) {
247
            $categoryModel = $dataManager->managerOptions['categorys']['model'];
248
            $model = $categoryModel::get($request['key'], $categoryModel::index(), $request['params']);
249
            if ($model) {
250
                $model->delete($request['params']);
251
            }
252
        }
253
        $result = new Server\Result();
254
        $result->send();
255
    }
256
257
}
258