Completed
Push — master ( c2ec3d...a14cfe )
by Alexey
05:11
created

DataManager::showCategory()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 35
Code Lines 18

Duplication

Lines 26
Ratio 74.29 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 26
loc 35
rs 6.7272
cc 7
eloc 18
nc 8
nop 2

1 Method

Rating   Name   Duplication   Size   Complexity  
B DataManager::checkAccess() 6 16 9
1
<?php
2
/**
3
 * Data manager
4
 *
5
 * @author Alexey Krupskiy <[email protected]>
6
 * @link http://inji.ru/
7
 * @copyright 2015 Alexey Krupskiy
8
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
9
 */
10
11
namespace Ui;
12
13
class DataManager extends \Object
14
{
15
    public $modelName = '';
16
    public $managerOptions = [];
17
    public $managerName = 'customManager';
18
    public $name = 'Менеджер данных';
19
    public $limit = 30;
20
    public $page = 1;
21
    public $table = null;
22
    public $joins = [];
23
    public $predraw = false;
24
    public $cols = [];
25
    public $managerId = '';
26
27
    /**
28
     * Construct new data manager
29
     * 
30
     * @param string $modelName
31
     * @param string|array $dataManager
32
     * @throws Exception
33
     */
34
    public function __construct($modelName, $dataManager = 'manager')
35
    {
36
        if (!class_exists($modelName)) {
37
            throw new \Exception("model {$modelName} not exists");
38
        }
39
40
        $this->modelName = $modelName;
41
42
        if (is_string($dataManager)) {
43
            $this->managerName = $dataManager;
44
            $dataManager = !empty($modelName::$dataManagers[$dataManager]) ? $modelName::$dataManagers[$dataManager] : [];
45
        }
46
        $this->managerOptions = $dataManager;
47
48
        if (!$this->managerOptions || !is_array($this->managerOptions)) {
49
            throw new \Exception('empty DataManager');
50
        }
51
52
        if (!empty($this->managerOptions['name'])) {
53
            $this->name = $this->managerOptions['name'];
54
        } elseif ($modelName && isset($modelName::$objectName)) {
55
            $this->name = $modelName::$objectName;
56
        } else {
57
            $this->name = $modelName;
58
        }
59
60
        $this->managerId = str_replace('\\', '_', 'dataManager_' . $this->modelName . '_' . $this->managerName . '_' . \Tools::randomString());
61
    }
62
63
    /**
64
     * Get buttons for manager
65
     * 
66
     * @param string $params
67
     * @param object $model
68
     */
69
    public function getButtons($params = [], $model = null)
70
    {
71
        $modelName = $this->modelName;
72
        $formParams = [
73
            'dataManagerParams' => $params,
74
            'formName' => !empty($this->managerOptions['editForm']) ? $this->managerOptions['editForm'] : 'manager'
75
        ];
76
        if ($model) {
77
            $formModelName = get_class($model);
78
            $relations = $formModelName::relations();
79
            $type = !empty($relations[$params['relation']]['type']) ? $relations[$params['relation']]['type'] : 'to';
80
            switch ($type) {
81
                case 'relModel':
82
                    $formParams['preset'] = [
83
                        $formModelName::index() => $model->pk()
84
                    ];
85
                    break;
86
                default:
87
                    $formParams['preset'] = [
88
                        $relations[$params['relation']]['col'] => $model->pk()
89
                    ];
90
            }
91
        }
92
93
        $buttons = [];
94
        if (!empty($this->managerOptions['sortMode'])) {
95
            $buttons[] = [
96
                'class' => 'modeBtn',
97
                'data-mode' => 'sort',
98
                'text' => 'Сортировать',
99
            ];
100
        }
101
        if (!empty($this->managerOptions['filters'])) {
102
            $buttons[] = [
103
                'text' => 'Фильтры',
104
                'onclick' => '  var modal = $("#' . $this->managerId . '_filters");
105
                modal.modal("show");',
106
            ];
107
        }
108
        $buttons[] = [
109
            'text' => 'Добавить элемент',
110
            'onclick' => 'inji.Ui.forms.popUp("' . str_replace('\\', '\\\\', $modelName) . '",' . json_encode($formParams) . ')',
111
        ];
112
113
        return $buttons;
114
    }
115
116
    function getActions()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
117
    {
118
        $actions = [
119
            'Open', 'Edit', 'Delete'
120
        ];
121
        if (isset($this->managerOptions['actions'])) {
122
            $actions = $this->managerOptions['actions'];
123
        }
124
        $return = [];
125
        foreach ($actions as $key => $action) {
126
            if (is_array($action)) {
127
                $return[$key] = $action;
128
            } else {
129
                $key = $action;
130
                $return[$key] = [
131
                    'className' => $action
132
                ];
133
            }
134
            $return[$key]['className'] = strpos($return[$key]['className'], '\\') === false && class_exists('Ui\DataManager\Action\\' . $return[$key]['className']) ? 'Ui\DataManager\Action\\' . $return[$key]['className'] : $action;
135
        }
136
        return $return;
137
    }
138
139
    /**
140
     * Get cols for manager
141
     * 
142
     * @return string
143
     */
144
    public function getCols()
145
    {
146
        $modelName = $this->modelName;
147
        if (!class_exists($modelName)) {
148
            return [];
149
        }
150
        $modelName = $this->modelName;
151
        $cols = [];
152
        $actions = $this->getActions();
153
        ob_start();
154
        ?>
155
        <div class="dropdown">
156
          <a id="dLabel" data-target="#" href="" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
157
            <i class="glyphicon glyphicon-cog"></i>
158
            <span class="caret"></span>
159
          </a>
160
161
          <ul class="dropdown-menu" aria-labelledby="dLabel">
162
            <li><a href ='' onclick='inji.Ui.dataManagers.get(this).rowSelection("selectAll");return false;'>Выделить все</a></li>
163
            <li><a href ='' onclick='inji.Ui.dataManagers.get(this).rowSelection("unSelectAll");return false;'>Снять все</a></li>
164
            <li><a href ='' onclick='inji.Ui.dataManagers.get(this).rowSelection("inverse");return false;'>Инвертировать</a></li>
165
            <li role="separator" class="divider"></li>
166
              <?php
167
              foreach ($actions as $action => $actionParams) {
168
                  if (class_exists($actionParams['className']) && $actionParams['className']::$groupAction) {
169
                      echo "<li><a href ='' onclick='inji.Ui.dataManagers.get(this).groupAction(\"" . str_replace('\\', '\\\\', $action) . "\");return false;'>{$actionParams['className']::$name}</a></li>";
170
                  }
171
              }
172
              ?>
173
          </ul>
174
        </div>
175
        <?php
176
        $dropdown = ob_get_contents();
177
        ob_end_clean();
178
        $cols[] = ['label' => $dropdown];
179
180
        $cols['id'] = ['label' => '№', 'sortable' => true];
181
        foreach ($this->managerOptions['cols'] as $key => $col) {
182
            if (is_array($col)) {
183
                $colName = $key;
184
                $colOptions = $col;
185
            } else {
186
                $colName = $col;
187
                $colOptions = [];
188
            }
189
            $colInfo = [];
190
            if ($modelName) {
191
                $colInfo = $modelName::getColInfo($colName);
192
            }
193
            if (empty($colOptions['label']) && !empty($colInfo['label'])) {
194
                $colOptions['label'] = $colInfo['label'];
195
            } elseif (empty($colOptions['label'])) {
196
                $colOptions['label'] = $colName;
197
            }
198
            $cols[$colName] = $colOptions;
199
        }
200
        return $cols;
201
    }
202
203
    /**
204
     * Get rows for manager
205
     * 
206
     * @param array $params
207
     * @param object $model
208
     * @return type
209
     */
210
    public function getRows($params = [], $model = null)
211
    {
212
        $modelName = $this->modelName;
213
        if (!class_exists($modelName)) {
214
            return [];
215
        }
216 View Code Duplication
        if (!$this->checkAccess()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
217
            $this->drawError('you not have access to "' . $this->modelName . '" manager with name: "' . $this->managerName . '"');
218
            return [];
219
        }
220
        $modelName = $this->modelName;
221
        $queryParams = [];
222
        if (empty($params['all'])) {
223
            if (!empty($params['limit'])) {
224
                $this->limit = (int) $params['limit'];
225
            }
226
            if (!empty($params['page'])) {
227
                $this->page = (int) $params['page'];
228
            }
229
            $queryParams['limit'] = $this->limit;
230
            $queryParams['start'] = $this->page * $this->limit - $this->limit;
231
        }
232 View Code Duplication
        if (!empty($params['categoryPath']) && $modelName::$categoryModel) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
233
            $queryParams['where'][] = ['tree_path', $params['categoryPath'] . '%', 'LIKE'];
234
        }
235
        if (!empty($params['appType'])) {
236
            $queryParams['appType'] = $params['appType'];
237
        }
238
        if ($this->joins) {
239
            $queryParams['joins'] = $this->joins;
240
        }
241 View Code Duplication
        if (!empty($this->managerOptions['userGroupFilter'][\Users\User::$cur->group_id]['getRows'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
242
            foreach ($this->managerOptions['userGroupFilter'][\Users\User::$cur->group_id]['getRows'] as $colName => $colOptions) {
243
                if (!empty($colOptions['userCol'])) {
244
                    if (strpos($colOptions['userCol'], ':')) {
245
                        $rel = substr($colOptions['userCol'], 0, strpos($colOptions['userCol'], ':'));
246
                        $param = substr($colOptions['userCol'], strpos($colOptions['userCol'], ':') + 1);
247
                        $queryParams['where'][] = [$colName, \Users\User::$cur->$rel->$param];
248
                    }
249
                } elseif (isset($colOptions['value'])) {
250
                    $queryParams['where'][] = [$colName, $colOptions['value']];
251
                }
252
            }
253
        }
254
        if (!empty($this->managerOptions['filters'])) {
255
            foreach ($this->managerOptions['filters'] as $col) {
256
                $colInfo = $modelName::getColInfo($col);
257
                switch ($colInfo['colParams']['type']) {
258 View Code Duplication
                    case 'select':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
259
                        if (empty($params['filters'][$col]['value'])) {
260
                            continue;
261
                        }
262
                        foreach ($params['filters'][$col]['value'] as $key => $value) {
263
                            if ($value === '') {
264
                                unset($params['filters'][$col]['value'][$key]);
265
                            }
266
                        }
267
                        if (!$params['filters'][$col]['value']) {
268
                            continue;
269
                        }
270
                        $queryParams['where'][] = [$col, implode(',', $params['filters'][$col]['value']), 'IN'];
271
                        break;
272
                    case 'bool':
273
274
                        if (!isset($params['filters'][$col]['value']) || $params['filters'][$col]['value'] === '') {
275
                            continue;
276
                        }
277
                        $queryParams['where'][] = [$col, $params['filters'][$col]['value']];
278
                        break;
279
                    case 'dateTime':
280 View Code Duplication
                    case 'date':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
281
                        if (empty($params['filters'][$col]['min']) && empty($params['filters'][$col]['max'])) {
282
                            continue;
283
                        }
284
                        if (!empty($params['filters'][$col]['min'])) {
285
                            $queryParams['where'][] = [$col, $params['filters'][$col]['min'], '>='];
286
                        }
287
                        if (!empty($params['filters'][$col]['max'])) {
288
                            if ($colInfo['colParams']['type'] == 'dateTime' && !strpos($params['filters'][$col]['max'], ' ')) {
289
290
                                $date = $params['filters'][$col]['max'] . ' 23:59:59';
291
                            } else {
292
                                $date = $params['filters'][$col]['max'];
293
                            }
294
                            $queryParams['where'][] = [$col, $date, '<='];
295
                        }
296
                        break;
297 View Code Duplication
                    case 'number':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
298
                        if (empty($params['filters'][$col]['min']) && empty($params['filters'][$col]['max'])) {
299
                            continue;
300
                        }
301
                        if (!empty($params['filters'][$col]['min'])) {
302
                            $queryParams['where'][] = [$col, $params['filters'][$col]['min'], '>='];
303
                        }
304
                        if (!empty($params['filters'][$col]['max'])) {
305
                            $queryParams['where'][] = [$col, $params['filters'][$col]['max'], '<='];
306
                        }
307
                        break;
308
                    case 'email':
309
                    case 'text':
310
                    case 'textarea':
311 View Code Duplication
                    case 'html':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
312
                        if (empty($params['filters'][$col]['value'])) {
313
                            continue;
314
                        }
315
                        switch ($params['filters'][$col]['compareType']) {
316
                            case 'contains':
317
                                $queryParams['where'][] = [$col, '%' . $params['filters'][$col]['value'] . '%', 'LIKE'];
318
                                break;
319
                            case 'equals':
320
                                $queryParams['where'][] = [$col, $params['filters'][$col]['value']];
321
                                break;
322
                            case 'starts_with':
323
                                $queryParams['where'][] = [$col, $params['filters'][$col]['value'] . '%', 'LIKE'];
324
                                break;
325
                            case 'ends_with':
326
                                $queryParams['where'][] = [$col, '%' . $params['filters'][$col]['value'], 'LIKE'];
327
                                break;
328
                        }
329
                        break;
330
                }
331
            }
332
        }
333
        if (!empty($params['mode']) && $params['mode'] == 'sort') {
334
            $queryParams['order'] = ['weight', 'asc'];
335
        } elseif (!empty($params['sortered']) && !empty($this->managerOptions['sortable'])) {
336
            foreach ($params['sortered'] as $key => $sortType) {
337
                $keys = array_keys($this->managerOptions['cols']);
338
                $colName = '';
339
                if (isset($keys[$key])) {
340
                    if (is_array($this->managerOptions['cols'][$keys[$key]])) {
341
                        $colName = $keys[$key];
342
                    } else {
343
                        $colName = $this->managerOptions['cols'][$keys[$key]];
344
                    }
345
                }
346
                if ($colName && in_array($colName, $this->managerOptions['sortable'])) {
347
                    $sortType = in_array($sortType, ['desc', 'asc']) ? $sortType : 'desc';
348
                    $queryParams['order'][] = [$colName, $sortType];
349
                }
350
            }
351
        }
352
        if ($model && !empty($params['relation'])) {
353
            $relation = $model::getRelation($params['relation']);
354
            $items = $model->$params['relation']($queryParams);
355
        } else {
356
            $relation = false;
357
            $items = $modelName::getList($queryParams);
358
        }
359
        $rows = [];
360
        foreach ($items as $item) {
361
            if ($relation && !empty($relation['relModel'])) {
362
                $item = $relation['relModel']::get([[$item->index(), $item->id], [$model->index(), $model->id]]);
363
            }
364
            $row = [];
365
            $row[] = '<input type ="checkbox" name = "pk[]" value =' . $item->pk() . '>';
366
            $row[] = $item->pk();
367
            foreach ($this->managerOptions['cols'] as $key => $colName) {
368
                if (!empty($params['download'])) {
369
                    $row[] = \Model::getColValue($item, is_array($colName) ? $key : $colName, true, false);
370
                } else {
371
                    $row[] = DataManager::drawCol($item, is_array($colName) ? $key : $colName, $params, $this);
372
                }
373
            }
374
            $row[] = $this->rowButtons($item, $params);
375
            $rows[] = $row;
376
        }
377
        return $rows;
378
    }
379
380
    public static function drawCol($item, $colName, $params = [], $dataManager = null, $originalCol = '', $originalItem = null)
1 ignored issue
show
Coding Style introduced by
drawCol uses the super-global variable $_SERVER 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...
381
    {
382
        $modelName = get_class($item);
383
        if (!class_exists($modelName)) {
384
            return false;
385
        }
386
387
        if (!$originalCol) {
388
            $originalCol = $colName;
389
        }
390
        if (!$originalItem) {
391
            $originalItem = $item;
392
        }
393
394
        $relations = $modelName::relations();
395
        if (strpos($colName, ':') !== false && !empty($relations[substr($colName, 0, strpos($colName, ':'))])) {
396
            $rel = substr($colName, 0, strpos($colName, ':'));
397
            $col = substr($colName, strpos($colName, ':') + 1);
398
            if ($item->$rel) {
399
                return DataManager::drawCol($item->$rel, $col, $params, $dataManager, $originalCol, $originalItem);
400
            } else {
401
                return 'Не указано';
402
            }
403
        }
404
        if (!empty($modelName::$cols[$colName]['relation'])) {
405
            $type = !empty($relations[$modelName::$cols[$colName]['relation']]['type']) ? $relations[$modelName::$cols[$colName]['relation']]['type'] : 'to';
406
            switch ($type) {
407 View Code Duplication
                case 'relModel':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
408
                    $managerParams = ['relation' => $modelName::$cols[$colName]['relation']];
409
                    $count = $item->{$modelName::$cols[$colName]['relation']}(array_merge($params, ['count' => 1]));
410
                    return "<a class = 'btn btn-xs btn-primary' onclick = 'inji.Ui.dataManagers.popUp(\"" . str_replace('\\', '\\\\', $modelName) . ":" . $item->pk() . "\"," . json_encode(array_merge($params, $managerParams)) . ")'>{$count} " . \Tools::getNumEnding($count, ['Элемент', 'Элемента', 'Элементов']) . "</a>";
411 View Code Duplication
                case 'many':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
412
                    $managerParams = ['relation' => $modelName::$cols[$colName]['relation']];
413
                    $count = $item->{$modelName::$cols[$colName]['relation']}(array_merge($params, ['count' => 1]));
414
                    return "<a class = 'btn btn-xs btn-primary' onclick = 'inji.Ui.dataManagers.popUp(\"" . str_replace('\\', '\\\\', $modelName) . ":" . $item->pk() . "\"," . json_encode(array_merge($params, $managerParams)) . ")'>{$count} " . \Tools::getNumEnding($count, ['Элемент', 'Элемента', 'Элементов']) . "</a>";
415
                default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

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

Loading history...
416
                    if ($item->{$modelName::$cols[$colName]['relation']}) {
417
                        if (\App::$cur->name == 'admin') {
418
                            $href = "<a href ='/admin/" . str_replace('\\', '/view/', $relations[$modelName::$cols[$colName]['relation']]['model']) . "/" . $item->{$modelName::$cols[$colName]['relation']}->pk() . "'>";
419
                            if (!empty($modelName::$cols[$colName]['showCol'])) {
420
                                $href .= $item->{$modelName::$cols[$colName]['relation']}->{$modelName::$cols[$colName]['showCol']};
421
                            } else {
422
423
                                $href .= $item->{$modelName::$cols[$colName]['relation']}->name();
424
                            }
425
                            $href .= '</a>';
426
                            return $href;
427
                        } else {
428
                            return $item->{$modelName::$cols[$colName]['relation']}->name();
429
                        }
430
                    } else {
431
                        return $item->$colName;
432
                    }
433
            }
434
        } else {
435
            if (!empty($modelName::$cols[$colName]['view']['type'])) {
436
                switch ($modelName::$cols[$colName]['view']['type']) {
437
                    case 'widget':
438
                        ob_start();
439
                        \App::$cur->view->widget($modelName::$cols[$colName]['view']['widget'], ['item' => $item, 'colName' => $colName, 'colParams' => $modelName::$cols[$colName]]);
440
                        $content = ob_get_contents();
441
                        ob_end_clean();
442
                        return $content;
443
                    case 'moduleMethod':
444
                        return \App::$cur->{$modelName::$cols[$colName]['view']['module']}->{$modelName::$cols[$colName]['view']['method']}($item, $colName, $modelName::$cols[$colName]);
445 View Code Duplication
                    case'many':
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...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
446
                        $managerParams = ['relation' => $modelName::$cols[$colName]['relation']];
447
                        $count = $item->{$modelName::$cols[$colName]['relation']}(array_merge($params, ['count' => 1]));
448
                        return "<a class = 'btn btn-xs btn-primary' onclick = 'inji.Ui.dataManagers.popUp(\"" . str_replace('\\', '\\\\', $modelName) . ":" . $item->pk() . "\"," . json_encode(array_merge($params, $managerParams)) . ")'>{$count} " . \Tools::getNumEnding($count, ['Элемент', 'Элемента', 'Элементов']) . "</a>";
449
                    default:
450
                        return $item->$colName;
451
                }
452
            } elseif (!empty($modelName::$cols[$colName]['type'])) {
453
                if (\App::$cur->name == 'admin' && $originalCol == 'name' || ( $dataManager && !empty($dataManager->managerOptions['colToView']) && $dataManager->managerOptions['colToView'] == $originalCol)) {
454
                    $formName = $dataManager && !empty($dataManager->managerOptions['editForm']) ? $dataManager->managerOptions['editForm'] : 'manager';
455
                    $redirectUrl = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/admin/' . str_replace('\\', '/', get_class($originalItem));
456
                    return "<a href ='/admin/" . str_replace('\\', '/view/', get_class($originalItem)) . "/{$originalItem->id}?formName={$formName}&redirectUrl={$redirectUrl}'>{$item->$colName}</a>";
457
                } elseif (\App::$cur->name == 'admin' && $colName == 'name') {
458
                    $redirectUrl = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/admin/' . str_replace('\\', '/', get_class($originalItem));
459
                    return "<a href ='/admin/" . str_replace('\\', '/view/', get_class($item)) . "/{$item->id}?redirectUrl={$redirectUrl}'>{$item->$colName}</a>";
460
                } else {
461
                    return \Model::resloveTypeValue($item, $colName);
462
                }
463
            } else {
464
                return $item->$colName;
465
            }
466
        }
467
    }
468
469
    public function rowButtons($item, $params)
470
    {
471
        $modelName = $this->modelName;
472
        if (!class_exists($modelName)) {
473
            return false;
474
        }
475
        ob_start();
476
        $widgetName = !empty($this->managerOptions['rowButtonsWidget']) ? $this->managerOptions['rowButtonsWidget'] : 'Ui\DataManager/rowButtons';
477
        \App::$cur->view->widget($widgetName, [
478
            'dataManager' => $this,
479
            'item' => $item,
480
            'params' => $params
481
        ]);
482
        $buttons = ob_get_contents();
483
        ob_end_clean();
484
        return $buttons;
485
    }
486
487
    public function getPages($params = [], $model = null)
488
    {
489
        $modelName = $this->modelName;
490
        if (!class_exists($modelName)) {
491
            return [];
492
        }
493 View Code Duplication
        if (!$this->checkAccess()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
494
            $this->drawError('you not have access to "' . $this->modelName . '" manager with name: "' . $this->managerName . '"');
495
            return [];
496
        }
497
        if (!empty($params['limit'])) {
498
            $this->limit = (int) $params['limit'];
499
        }
500
        if (!empty($params['page'])) {
501
            $this->page = (int) $params['page'];
502
        }
503
        $queryParams = [
504
            'count' => true
505
        ];
506
        $modelName = $this->modelName;
507 View Code Duplication
        if (!empty($params['categoryPath']) && $modelName::$categoryModel) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
508
            $queryParams['where'][] = ['tree_path', $params['categoryPath'] . '%', 'LIKE'];
509
        }
510 View Code Duplication
        if (!empty($this->managerOptions['userGroupFilter'][\Users\User::$cur->group_id]['getRows'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
511
            foreach ($this->managerOptions['userGroupFilter'][\Users\User::$cur->group_id]['getRows'] as $colName => $colOptions) {
512
                if (!empty($colOptions['userCol'])) {
513
                    if (strpos($colOptions['userCol'], ':')) {
514
                        $rel = substr($colOptions['userCol'], 0, strpos($colOptions['userCol'], ':'));
515
                        $param = substr($colOptions['userCol'], strpos($colOptions['userCol'], ':') + 1);
516
                        $queryParams['where'][] = [$colName, \Users\User::$cur->$rel->$param];
517
                    }
518
                } elseif (isset($colOptions['value'])) {
519
                    $queryParams['where'][] = [$colName, $colOptions['value']];
520
                }
521
            }
522
        }
523
        $modelName = $this->modelName;
524
        if (!empty($this->managerOptions['filters'])) {
525
            foreach ($this->managerOptions['filters'] as $col) {
526
                $colInfo = $modelName::getColInfo($col);
527
                switch ($colInfo['colParams']['type']) {
528 View Code Duplication
                    case 'select':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
529
                        if (empty($params['filters'][$col]['value'])) {
530
                            continue;
531
                        }
532
                        foreach ($params['filters'][$col]['value'] as $key => $value) {
533
                            if ($value === '') {
534
                                unset($params['filters'][$col]['value'][$key]);
535
                            }
536
                        }
537
                        if (!$params['filters'][$col]['value']) {
538
                            continue;
539
                        }
540
                        $queryParams['where'][] = [$col, implode(',', $params['filters'][$col]['value']), 'IN'];
541
                        break;
542
                    case 'bool':
543
544
                        if (empty($params['filters'][$col]['value'])) {
545
                            continue;
546
                        }
547
                        $queryParams['where'][] = [$col, '1'];
548
                        break;
549
                    case 'dateTime':
550 View Code Duplication
                    case 'date':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
551
                        if (empty($params['filters'][$col]['min']) && empty($params['filters'][$col]['max'])) {
552
                            continue;
553
                        }
554
                        if (!empty($params['filters'][$col]['min'])) {
555
                            $queryParams['where'][] = [$col, $params['filters'][$col]['min'], '>='];
556
                        }
557
                        if (!empty($params['filters'][$col]['max'])) {
558
                            if ($colInfo['colParams']['type'] == 'dateTime' && !strpos($params['filters'][$col]['max'], ' ')) {
559
560
                                $date = $params['filters'][$col]['max'] . ' 23:59:59';
561
                            } else {
562
                                $date = $params['filters'][$col]['max'];
563
                            }
564
                            $queryParams['where'][] = [$col, $date, '<='];
565
                        }
566
                        break;
567 View Code Duplication
                    case 'number':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
568
                        if (empty($params['filters'][$col]['min']) && empty($params['filters'][$col]['max'])) {
569
                            continue;
570
                        }
571
                        if (!empty($params['filters'][$col]['min'])) {
572
                            $queryParams['where'][] = [$col, $params['filters'][$col]['min'], '>='];
573
                        }
574
                        if (!empty($params['filters'][$col]['max'])) {
575
                            $queryParams['where'][] = [$col, $params['filters'][$col]['max'], '<='];
576
                        }
577
                        break;
578
                    case 'email':
579
                    case 'text':
580
                    case 'textarea':
581 View Code Duplication
                    case 'html':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
582
                        if (empty($params['filters'][$col]['value'])) {
583
                            continue;
584
                        }
585
                        switch ($params['filters'][$col]['compareType']) {
586
                            case 'contains':
587
                                $queryParams['where'][] = [$col, '%' . $params['filters'][$col]['value'] . '%', 'LIKE'];
588
                                break;
589
                            case 'equals':
590
                                $queryParams['where'][] = [$col, $params['filters'][$col]['value']];
591
                                break;
592
                            case 'starts_with':
593
                                $queryParams['where'][] = [$col, $params['filters'][$col]['value'] . '%', 'LIKE'];
594
                                break;
595
                            case 'ends_with':
596
                                $queryParams['where'][] = [$col, '%' . $params['filters'][$col]['value'], 'LIKE'];
597
                                break;
598
                        }
599
                        break;
600
                }
601
            }
602
        }
603
        if ($model && !empty($params['relation'])) {
604
            $count = $model->$params['relation']($queryParams);
605
        } else {
606
            $count = $modelName::getCount($queryParams);
607
        }
608
        $pages = new Pages([
609
            'limit' => $this->limit,
610
            'page' => $this->page,
611
                ], [
612
            'count' => $count,
613
            'dataManager' => $this
614
        ]);
615
        return $pages;
616
    }
617
618
    public function preDraw($params = [], $model = null)
619
    {
620
        if (!class_exists($this->modelName)) {
621
            return false;
622
        }
623
        $this->predraw = true;
624
625
        $cols = $this->getCols();
626
627
        $this->table = new Table();
628
        $tableCols = [];
629
        foreach ($cols as $colName => $colOptions) {
630
            $tableCols[] = !empty($colOptions['label']) ? $colOptions['label'] : $colName;
631
        }
632
        $tableCols[] = '';
633
        $this->table->setCols($tableCols);
634
    }
635
636
    public function draw($params = [], $model = null)
637
    {
638
        if (!class_exists($this->modelName)) {
639
            return false;
640
        }
641
        if (!$this->predraw) {
642
            $this->preDraw($params, $model);
643
        }
644
        \App::$cur->view->widget('Ui\DataManager/DataManager', [
645
            'dataManager' => $this,
646
            'model' => $model,
647
            'table' => $this->table,
648
            'params' => $params
649
        ]);
650
    }
651
652
    public function drawCategorys()
653
    {
654
        if (!class_exists($this->modelName)) {
655
            return false;
656
        }
657 View Code Duplication
        if (!$this->checkAccess()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
658
            $this->drawError('you not have access to "' . $this->modelName . '" manager with name: "' . $this->managerName . '"');
659
            return [];
660
        }
661
        $tree = new Tree();
662
        $tree->ul($this->managerOptions['categorys']['model'], 0, function($category) {
663
            return "<a href='#' onclick='inji.Ui.dataManagers.get(this).switchCategory(this);return false;' data-path ='" . $category->tree_path . ($category->pk() ? $category->pk() . "/" : '') . "'> " . $category->name . "</a> 
664
                                    <a href = '#' onclick = 'inji.Ui.forms.popUp(\"" . str_replace('\\', '\\\\', get_class($category)) . ':' . $category->pk() . "\")' class ='glyphicon glyphicon-edit'></a>&nbsp;    
665
                <a onclick='inji.Ui.dataManagers.get(this).delCategory({$category->pk()});return false;' class ='glyphicon glyphicon-remove'></a>";
666
        });
667
        ?>
668
        <?php
669
    }
670
671
    /**
672
     * Draw error message
673
     * 
674
     * @param string $errorText
675
     */
676
    public function drawError($errorText)
677
    {
678
        echo $errorText;
679
    }
680
681
    /**
682
     * Check access cur user to manager with name in param
683
     * 
684
     * @return boolean
685
     */
686
    public function checkAccess()
687
    {
688
        if (\App::$cur->Access && !\App::$cur->Access->checkAccess($this)) {
689
            return false;
690
        }
691 View Code Duplication
        if (!empty($this->managerOptions['options']['access']['apps']) && !in_array(\App::$cur->name, $this->managerOptions['options']['access']['apps'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
692
            return false;
693
        }
694 View Code Duplication
        if (!empty($this->managerOptions['options']['access']['groups']) && !in_array(\Users\User::$cur->group_id, $this->managerOptions['options']['access']['groups'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
695
            return false;
696
        }
697
        if ($this->managerName == 'manager' && !\Users\User::$cur->isAdmin()) {
698
            return false;
699
        }
700
        return true;
701
    }
702
703
}
704