Completed
Push — master ( 0afdc4...0e57e6 )
by Alexey
04:27
created

DataManagerController::loadRowsAction()   D

Complexity

Conditions 15
Paths 200

Size

Total Lines 77
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 55
nc 200
nop 0
dl 0
loc 77
rs 4.8381
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 {
12
13
  public function parseRequest() {
14
    $return = [];
15
    $return['params'] = UserRequest::get('params', 'array', []);
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 (!$return['managerName']) {
57
      $return['managerName'] = 'manager';
58
    }
59
60
    return $return;
61
  }
62
63
  public function indexAction() {
64
    $result = new Server\Result();
65
66
    ob_start();
67
68
    $request = $this->parseRequest();
69
70
    $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
71
    $dataManager->draw($request['params'], $request['model']);
72
73
    $result->content = ob_get_contents();
74
75
    ob_end_clean();
76
77
    $result->send();
78
  }
79
80
  public function loadRowsAction() {
81
    $result = new Server\Result();
82
    $result->content = [];
83
84
    ob_start();
85
86
    $request = $this->parseRequest();
87
88
    $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
89
    if ($request['download']) {
90
91
      ini_set('memory_limit', '2000M');
92
      set_time_limit(0);
93
94
      $request['params']['all'] = true;
95
      $request['params']['download'] = true;
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, 1);
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
    if (!$request['params']['all']) {
117
      $pages = $dataManager->getPages($request['params'], $request['model']);
118
      $request['params']['page'] = !empty($pages->params['page']) ? $pages->params['page'] : $dataManager->page;
119
      $request['params']['limit'] = !empty($pages->params['limit']) ? $pages->params['limit'] : $dataManager->limit;
120
    }
121
    $rows = $dataManager->getRows($request['params'], $request['model']);
122
    foreach ($rows as $row) {
123
      if ($request['download']) {
124
        $row = array_slice($row, 1, -1);
125
        foreach ($row as $col) {
126
          if (!$endRow) {
127
            echo ";";
128
          }
129
          $endRow = false;
130
          echo '"' . str_replace(["\n", '"'], ['“'], $col) . '"';
131
        }
132
        echo "\n";
133
        $endRow = true;
134
      } else {
135
        Ui\Table::drawRow($row);
136
      }
137
    }
138
    if ($request['download']) {
139
      exit();
140
    }
141
142
    $result->content['rows'] = ob_get_contents();
143
    ob_clean();
144
145
    $result->content['pages'] = '';
146
147
    if (isset($pages) && $pages) {
148
      if ($pages) {
149
        $pages->draw();
150
        echo '<div style="background:#fff;">записей: <b>' . $pages->options['count'] . '</b>. страница <b>' . $pages->params['page'] . '</b> из <b>' . $pages->params['pages'] . '</b></div>';
151
      }
152
      $result->content['pages'] = ob_get_contents();
153
      ob_end_clean();
154
    }
155
    $result->send();
156
  }
157
158
  public function loadCategorysAction() {
159
    $result = new Server\Result();
160
161
    ob_start();
162
163
    $request = $this->parseRequest();
164
165
    $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
166
    $dataManager->drawCategorys();
167
168
    $result->content = ob_get_contents();
169
    ob_end_clean();
170
171
    $result->send();
172
  }
173
174 View Code Duplication
  public function delRowAction() {
175
176
    $request = $this->parseRequest();
177
178
    $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
179
180
    if ($dataManager->checkAccess()) {
181
      $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
182
      if ($model) {
183
        $model->delete($request['params']);
184
      }
185
    }
186
    $result = new Server\Result();
187
    $result->successMsg = empty($request['silence']) ? 'Запись удалена' : '';
188
    $result->send();
189
  }
190
191
  public function updateRowAction() {
192
193
    $request = $this->parseRequest();
194
195
    $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
196
197
    if ($dataManager->checkAccess()) {
198
      $model = $request['modelName']::get($request['key'], $request['modelName']::index(), $request['params']);
199
      if ($model) {
200
        $model->{$request['col']} = $request['col_value'];
201
        $model->save($request['params']);
202
      }
203
    }
204
    $result = new Server\Result();
205
    $result->successMsg = empty($request['silence']) ? 'Запись Обновлена' : '';
206
    $result->send();
207
  }
208
209
  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...
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
    $request = $this->parseRequest();
242
243
    $dataManager = new Ui\DataManager($request['modelName'], $request['managerName']);
244
245
    if ($dataManager->checkAccess() && !empty($dataManager->managerOptions['categorys'])) {
246
      $categoryModel = $dataManager->managerOptions['categorys']['model'];
247
      $model = $categoryModel::get($request['key'], $categoryModel::index(), $request['params']);
248
      if ($model) {
249
        $model->delete($request['params']);
250
      }
251
    }
252
    $result = new Server\Result();
253
    $result->send();
254
  }
255
256
}
257