Completed
Push — master ( 65cb7c...c99a2b )
by Alexey
07:25
created

DataManagerController   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 250
Duplicated Lines 13.6 %

Coupling/Cohesion

Components 1
Dependencies 5
Metric Value
wmc 45
lcom 1
cbo 5
dl 34
loc 250
rs 8.3673

8 Methods

Rating   Name   Duplication   Size   Complexity  
B parseRequest() 0 46 6
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
C groupActionAction() 0 38 12
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
17
        $return['params'] = filter_var(INPUT_GET, 'params', FILTER_FORCE_ARRAY);
18
        $item = filter_var(INPUT_GET, 'item', FILTER_SANITIZE_STRING);
19
20
        if (strpos($item, ':')) {
21
            $raw = explode(':', $item);
22
            $return['modelName'] = $raw[0];
23
            $return['model'] = $modelName::get($raw[1], $modelName::index(), $params);
0 ignored issues
show
Bug introduced by
The variable $modelName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $params does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
24
        } else {
25
            $return['modelName'] = $item;
26
            $return['model'] = null;
27
        }
28
        if (!empty($return['params']['relation'])) {
29
            $relation = $modelName::getRelation($return['params']['relation']);
30
            if (!empty($relation['type']) && $relation['type'] == 'telModlel') {
31
                $return['modelName'] = $relation['relModel'];
32
            } else {
33
                $return['modelName'] = $relation['model'];
34
            }
35
        }
36
        $return['params']['filters'] = filter_var(INPUT_GET, 'filters', FILTER_FORCE_ARRAY);
37
        $return['params']['sortered'] = filter_var(INPUT_GET, 'sortered', FILTER_FORCE_ARRAY);
38
        $return['params']['mode'] = filter_var(INPUT_GET, 'mode', FILTER_SANITIZE_STRING);
39
        $return['params']['all'] = filter_var(INPUT_GET, 'all', FILTER_VALIDATE_BOOLEAN);
40
41
        $return['key'] = filter_var(INPUT_GET, 'key', FILTER_SANITIZE_NUMBER_INT);
42
        $return['col'] = filter_var(INPUT_GET, 'col', FILTER_SANITIZE_STRING);
43
        $return['col_value'] = filter_var(INPUT_GET, 'col_value', FILTER_SANITIZE_STRING);
44
45
        $return['action'] = filter_var(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
46
        $return['ids'] = filter_var(INPUT_GET, 'ids', FILTER_SANITIZE_STRING);
47
        $return['adInfo'] = filter_var(INPUT_GET, 'adInfo', FILTER_FORCE_ARRAY);
48
49
        $return['download'] = filter_var(INPUT_GET, 'download', FILTER_VALIDATE_BOOLEAN);
50
        $return['silence'] = filter_var(INPUT_GET, 'silence', FILTER_VALIDATE_BOOLEAN);
51
52
        $return['managerName'] = filter_var(INPUT_GET, 'managerName', FILTER_SANITIZE_STRING);
53
        if (!$return['managerName']) {
54
            $return['managerName'] = 'manager';
55
        }
56
57
        return $return;
58
    }
59
60
    public function indexAction($action = '')
0 ignored issues
show
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
61
    {
62
        $result = new Server\Result();
63
64
        ob_start();
65
66
        $request = $this->parseRequest();
67
68
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
69
        $dataManager->draw($request['params'], $request['model']);
70
71
        $result->content = ob_get_contents();
72
73
        ob_end_clean();
74
75
        $result->send();
76
    }
77
78
    public function loadRowsAction()
79
    {
80
        $result = new Server\Result();
81
        $result->content = [];
82
83
        ob_start();
84
85
        $request = $this->parseRequest();
86
87
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
88
        if ($request['download']) {
89
            $request['params']['all'] = true;
90
            $request['params']['download'] = true;
91
            set_time_limit(0);
92
            ob_end_clean();
93
            header('Content-Encoding: UTF-8');
94
            header("Content-Type: text/csv");
95
            header("Content-Disposition: attachment; filename=" . $request['modelName']::$objectName . '.csv');
96
            echo "\xEF\xBB\xBF"; // UTF-8 BOM
97
98
99
            $cols = $dataManager->getCols();
100
            $cols = array_slice($cols, (!empty($dataManager->managerOptions['groupActions']) ? 1 : 0));
101
            $endRow = true;
102
            foreach ($cols as $colName => $options) {
103
                if (!$endRow) {
104
                    echo ";";
105
                }
106
                $endRow = false;
107
                echo '"' . $options['label'] . '"';
108
            }
109
            echo "\n";
110
            $endRow = true;
111
        }
112
        $rows = $dataManager->getRows($request['params'], $request['model']);
113
        foreach ($rows as $row) {
114
            if ($request['download']) {
115
                $row = array_slice($row, (!empty($dataManager->managerOptions['groupActions']) ? 1 : 0), -1);
116
                foreach ($row as $col) {
117
                    if (!$endRow) {
118
                        echo ";";
119
                    }
120
                    $endRow = false;
121
                    echo '"' . str_replace("\n", '', $col) . '"';
122
                }
123
                echo "\n";
124
                $endRow = true;
125
            } else {
126
                Ui\Table::drawRow($row);
127
            }
128
        }
129
        if ($request['download']) {
130
            exit();
131
        }
132
133
        $result->content['rows'] = ob_get_contents();
134
        ob_clean();
135
136
        $result->content['pages'] = '';
137
138
        if (!$request['params']['all']) {
139
            $pages = $dataManager->getPages($request['params'], $model);
0 ignored issues
show
Bug introduced by
The variable $model does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
140
            if ($pages) {
141
                $pages->draw();
142
            }
143
            $result->content['pages'] = ob_get_contents();
144
            ob_end_clean();
145
        }
146
        $result->send();
147
    }
148
149
    public function loadCategorysAction()
150
    {
151
        $result = new Server\Result();
152
153
        ob_start();
154
155
        $request = $this->parseRequest();
156
157
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
158
        $dataManager->drawCategorys();
159
160
        $result->content = ob_get_contents();
161
        ob_end_clean();
162
163
        $result->send();
164
    }
165
166 View Code Duplication
    public function delRowAction()
167
    {
168
169
        $request = $this->parseRequest();
170
171
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
172
173
        if ($dataManager->checkAccess()) {
174
            $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
175
            if ($model) {
176
                $model->delete($request['params']);
177
            }
178
        }
179
        $result = new Server\Result();
180
        $result->successMsg = empty($request['silence']) ? 'Запись удалена' : '';
181
        $result->send();
182
    }
183
184
    public function updateRowAction()
185
    {
186
187
        $request = $this->parseRequest();
188
189
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
190
191
        if ($dataManager->checkAccess()) {
192
            $model = $modelName::get($request['key'], $request['modelName']::index(), $request['params']);
0 ignored issues
show
Bug introduced by
The variable $modelName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
193
            if ($model) {
194
                $model->{$request['col']} = $request['col_value'];
195
                $model->save($params);
0 ignored issues
show
Bug introduced by
The variable $params does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
196
            }
197
        }
198
        $result = new Server\Result();
199
        $result->successMsg = empty($request['silence']) ? 'Запись Обновлена' : '';
200
        $result->send();
201
    }
202
203
    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...
204
    {
205
        $request = $this->parseRequest();
206
207
        $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
208
209
        if ($dataManager->checkAccess()) {
210
            if (!empty($request['action']) && !empty($dataManager->managerOptions['groupActions'][$request['action']]) && trim($request['ids'], ' ,')) {
211
                $ids = trim($request['ids'], ' ,');
212
                $action = $dataManager->managerOptions['groupActions'][$request['action']];
213
                switch ($action['action']) {
214
                    case'delete':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
215
                        $models = $request['modelName']::getList(['where' => [[$request['modelName']::index(), $ids, 'IN']]]);
216
                        foreach ($models as $model) {
217
                            $model->delete();
218
                        }
219
                        break;
220
                    case 'changeParam':
221
                        $models = $request['modelName']::getList(['where' => [[$request['modelName']::index(), $ids, 'IN']]]);
222
                        foreach ($models as $model) {
223
                            $model->{$action['col']} = $action['value'];
224
                            $model->save(!empty($_GET['params']) ? $_GET['params'] : []);
225
                        }
226
                        break;
227
                    case 'moduleMethod':
228
                        $comandResult = App::$cur->{$action['module']}->{$action['method']}($dataManager, $ids, $request['adInfo']);
229
                        break;
230
                }
231
            }
232
        }
233
        $result = new Server\Result();
234
        if (!empty($comandResult)) {
235
            $result->success = $comandResult['success'];
236
            $result->content = $comandResult['content'];
237
        }
238
        $result->successMsg = 'Операция выполнена';
239
        $result->send();
240
    }
241
242 View Code Duplication
    public function delCategoryAction()
243
    {
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
260
}
261