AbstractGrid::setBottomNavigationBar()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/**
3
 * @company MTE Telecom, Ltd.
4
 * @author Roman Malashin <[email protected]>
5
 */
6
7
namespace Nnx\DataGrid;
8
9
use Nnx\DataGrid\Column\ColumnInterface;
10
use Nnx\DataGrid\Adapter\AdapterInterface;
11
use Nnx\DataGrid\NavigationBar\NavigationBarInterface;
12
use Nnx\DataGrid\Column\GridColumnPluginManager;
13
use Nnx\DataGrid\Column\GridColumnPluginManagerAwareTrait;
14
use Nnx\DataGrid\Mutator\GridMutatorPluginManager;
15
use Nnx\DataGrid\Mutator\GridMutatorPluginManagerAwareTrait;
16
use Nnx\DataGrid\Mutator\MutatorInterface;
17
use Traversable;
18
use ArrayAccess;
19
20
/**
21
 * Class AbstractGrid
22
 * @package Nnx\DataGrid
23
 */
24
abstract class AbstractGrid implements GridInterface
25
{
26
27
    use GridColumnPluginManagerAwareTrait;
28
    use GridMutatorPluginManagerAwareTrait;
29
    /**
30
     * Условия для фильтрации выбираемых данных
31
     * @var array | Traversable
32
     */
33
    protected $conditions;
34
35
    /**
36
     * Адаптер с помощью которого будет осуществляться выборка данных
37
     * @var AdapterInterface
38
     */
39
    protected $adapter;
40
41
    /**
42
     * Коллекция колонок таблицы
43
     * @var array | Traversable
44
     */
45
    protected $columns;
46
47
    /**
48
     * Опции таблицы
49
     * @var array | Traversable
50
     */
51
    protected $options;
52
53
    /**
54
     * Имя таблицы
55
     * @var string
56
     */
57
    protected $name;
58
59
    /**
60
     * Массив атрибутов таблицы для отображения
61
     * @var array
62
     */
63
    protected $attributes = [];
64
65
    /**
66
     * Мутаторы для строк
67
     * @var array | ArrayAccess
68
     */
69
    protected $mutators = [];
70
71
    /**
72
     * @var NavigationBarInterface
73
     */
74
    protected $topNavigationBar;
75
76
    /**
77
     * @var NavigationBarInterface
78
     */
79
    protected $bottomNavigationBar;
80
81
82
    /**
83
     * Конструкто класса
84
     * @param array | ArrayAccess $options
85
     * @throws Exception\InvalidArgumentException
86
     */
87
    public function __construct(array $options = [])
88
    {
89
        if (!array_key_exists('adapter', $options) || !$options['adapter']) {
90
            throw new Exception\InvalidArgumentException(
91
                'Для корректной работы таблиц в конструктор необходимо передавать адаптер.'
92
            );
93
        }
94
        $adapter = $options['adapter'];
95
        unset($options['adapter']);
96
97
        $name = array_key_exists('name', $options) ? $options['name'] : null;
98
        unset($options['name']);
99
        $this->setName($name);
100
101
        if (!array_key_exists('columnPluginManager', $options) || !$options['columnPluginManager']) {
102
            throw new Exception\InvalidArgumentException(
103
                'Для корректной работы таблиц должна передаваться GridColumnPluginManager в конструктор таблиц.'
104
            );
105
        }
106
        $columnPluginManager = $options['columnPluginManager'];
107
        unset($options['columnPluginManager']);
108
109
        if (!array_key_exists('mutatorPluginManager', $options) || !$options['mutatorPluginManager']) {
110
            throw new Exception\InvalidArgumentException(
111
                'Для корректной работы таблиц должна передаваться GridMutatorPluginManager.'
112
            );
113
        }
114
        $mutatorPluginManager = $options['mutatorPluginManager'];
115
        unset($options['mutatorPluginManager']);
116
117
        $topNavigationBar = !empty($options['topNavigationBar']) ? $options['topNavigationBar'] : null;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
118
        $bottomNavigationBar = !empty($options['bottomNavigationBar']) ? $options['bottomNavigationBar'] : null;
119
        unset($options['topNavigationBar'], $options['bottomNavigationBar']);
120
121
        $this->configure($mutatorPluginManager, $adapter, $columnPluginManager, $topNavigationBar, $bottomNavigationBar);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
122
        $this->setOptions($options);
123
    }
124
125
    /**
126
     * Конфигурируем адаптер грида
127
     * @param GridMutatorPluginManager $mutatorPluginManager
128
     * @param AdapterInterface $adapter
129
     * @param GridColumnPluginManager $columnPluginManager
130
     * @param NavigationBarInterface $topNavigationBar
0 ignored issues
show
Documentation introduced by
Should the type for parameter $topNavigationBar not be null|NavigationBarInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
131
     * @param NavigationBarInterface $bottomNavigationBar
0 ignored issues
show
Documentation introduced by
Should the type for parameter $bottomNavigationBar not be null|NavigationBarInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
132
     * @internal param array $options
133
     */
134
    protected function configure(
135
        GridMutatorPluginManager $mutatorPluginManager,
136
        AdapterInterface $adapter,
137
        GridColumnPluginManager $columnPluginManager,
138
        NavigationBarInterface $topNavigationBar = null,
139
        NavigationBarInterface $bottomNavigationBar = null)
140
    {
141
        $this->setMutatorPluginManager($mutatorPluginManager);
142
        $this->setAdapter($adapter);
143
        $this->setColumnPluginManager($columnPluginManager);
144
        $this->setTopNavigationBar($topNavigationBar);
0 ignored issues
show
Bug introduced by
It seems like $topNavigationBar defined by parameter $topNavigationBar on line 138 can be null; however, Nnx\DataGrid\AbstractGrid::setTopNavigationBar() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
145
        $this->setBottomNavigationBar($bottomNavigationBar);
0 ignored issues
show
Bug introduced by
It seems like $bottomNavigationBar defined by parameter $bottomNavigationBar on line 139 can be null; however, Nnx\DataGrid\AbstractGri...etBottomNavigationBar() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
146
    }
147
148
149
    /**
150
     * Условия для фильтрации выбираемых данных
151
     * @param array | Traversable $conditions
152
     * @return $this
153
     */
154
    public function setConditions($conditions)
155
    {
156
        $this->conditions = $conditions;
157
        $this->getAdapter()->setConditions($conditions);
158
        return $this;
159
    }
160
161
    /**
162
     * Возвращает набор условий по которым фильтровать выборку
163
     * @return array
164
     */
165
    public function getConditions()
166
    {
167
        return $this->conditions;
168
    }
169
170
    /**
171
     * Устанавливает адаптер
172
     * @param AdapterInterface  $adapter
173
     * @return $this
174
     */
175
    public function setAdapter($adapter)
176
    {
177
        $this->adapter = $adapter;
178
        return $this;
179
    }
180
181
    /**
182
     * Возвращает адаптер с помощью которого будет осуществляться выборка данных
183
     * @return AdapterInterface
184
     */
185
    public function getAdapter()
186
    {
187
        return $this->adapter;
188
    }
189
190
    /**
191
     * Возвращает коллекцию колонок
192
     * @return array | Traversable
193
     */
194
    public function getColumns()
195
    {
196
        return $this->columns;
197
    }
198
199
    /**
200
     * Добавление колонок в таблицу
201
     * @param array | Traversable $columns
202
     * @return $this
203
     */
204
    public function setColumns($columns)
205
    {
206
        $this->columns = $columns;
207
        return $this;
208
    }
209
210
    /**
211
     * Добавление колонки в таблицу
212
     * @param ColumnInterface|array|ArrayAccess $column
213
     * @return $this
214
     * @throws Column\Exception\InvalidColumnException
215
     * @throws Exception\InvalidArgumentException
216
     * @throws Exception\RuntimeException
217
     */
218
    public function add($column)
219
    {
220
        if (is_array($column) || $column instanceof ArrayAccess) {
221
            if (!array_key_exists('type', $column)) {
222
                throw new Column\Exception\InvalidColumnException(
223
                    'Не передан тип создаваемого столбца.'
224
                );
225
            }
226
            $column['columnPluginManager'] = $this->getColumnPluginManager();
227
            if (!$this->getColumnPluginManager()->has($column['type'])) {
228
                throw new Exception\RuntimeException(sprintf('Колонка с именем %s не найдена', $column['type']));
229
            }
230
            /** @var ColumnInterface $column */
231
            $column = $this->getColumnPluginManager()->get($column['type'], $column);
0 ignored issues
show
Documentation introduced by
$column is of type object<Nnx\DataGrid\Column\ColumnInterface>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
232
        } elseif (!$column instanceof ColumnInterface) {
233
            throw new Exception\InvalidArgumentException(
234
                sprintf('Column должен быть массивом или реализовывать %s', ColumnInterface::class)
235
            );
236
        }
237
        $this->columns[$column->getName()] = $column;
238
        return $this;
239
    }
240
241
    /**
242
     * Удаляет колонку с именем $name из таблицы
243
     * @param string $name
244
     * @return $this
245
     */
246
    public function remove($name)
247
    {
248
        $name = strtolower($name);
249
        if (array_key_exists($name, $this->columns)) {
250
            unset($this->columns[$name]);
251
        }
252
        return $this;
253
    }
254
255
    /**
256
     * Возвращает колонку грида
257
     * @param string $name
258
     * @return ColumnInterface
259
     * @throws Exception\InvalidArgumentException
260
     */
261
    public function get($name)
262
    {
263
        if (!is_string($name)) {
264
            throw new Exception\InvalidArgumentException('Имя получаемой колонки должно быть строкой.');
265
        }
266
        $name = strtolower($name);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
267
        $column = null;
268
        if (array_key_exists($name, $this->columns)) {
269
            $column = $this->columns[$name];
270
        }
271
        return $column;
272
    }
273
274
    /**
275
     * Опции таблицы
276
     * @param array | Traversable $options
277
     * @return $this
278
     */
279
    public function setOptions($options)
280
    {
281
        $this->options = $options;
282
        return $this;
283
    }
284
285
    /**
286
     * Возвращает массив опции таблицы
287
     * @return array | Traversable
288
     */
289
    public function getOptions()
290
    {
291
        return $this->options;
292
    }
293
294
    /**
295
     * Устанавливает имя таблицы
296
     * @param string $name
297
     * @return $this
298
     */
299
    public function setName($name)
300
    {
301
        $this->name = $name;
302
        return $this;
303
    }
304
305
    /**
306
     * Возвращает имя таблицы
307
     * @return string
308
     */
309
    public function getName()
310
    {
311
        return $this->name;
312
    }
313
314
    /**
315
     * Возвращает атрибуты используемые при отображении грида
316
     * @return array
317
     */
318
    public function getAttributes()
319
    {
320
        return $this->attributes;
321
    }
322
323
    /**
324
     * Устанавливает используемые для отображения грида
325
     * @param array $attributes
326
     * @return $this
327
     */
328
    public function setAttributes(array $attributes)
329
    {
330
        $this->attributes = $attributes;
331
        return $this;
332
    }
333
334
    /**
335
     * Добавляет атрибут для таблицы
336
     * @param string $key
337
     * @param mixed $value
338
     * @return $this
339
     */
340
    public function addAttribute($key, $value)
341
    {
342
        $this->attributes[$key] = $value;
343
        return $this;
344
    }
345
346
    /**
347
     * Возвращает набор мутаторов для строк таблицы
348
     * @return array|ArrayAccess
349
     */
350
    public function getMutators()
351
    {
352
        return $this->mutators;
353
    }
354
355
    /**
356
     * Устанавливает набор мутаторов для строк таблицы
357
     * @param array|ArrayAccess $mutators
358
     * @return $this
359
     */
360
    public function setMutators(array $mutators)
361
    {
362
        $this->mutators = $mutators;
363
        return $this;
364
    }
365
366
    /**
367
     * Добавляет мутатор для строк таблицы
368
     * @param MutatorInterface|array|ArrayAccess $mutator
369
     * @return $this
370
     * @throws Mutator\Exception\RuntimeException
371
     */
372
    public function addMutator($mutator)
373
    {
374
        if (is_array($mutator) || $mutator instanceof MutatorInterface) {
375
            if (!array_key_exists('type', $mutator) || !$mutator['type']) {
376
                throw new Mutator\Exception\RuntimeException('Не задан тип мутатора.');
377
            }
378
            $mutator = $this->getMutatorPluginManager()->get($mutator['type'], $mutator);
0 ignored issues
show
Bug introduced by
It seems like $mutator defined by $this->getMutatorPluginM...ator['type'], $mutator) on line 378 can also be of type object<Nnx\DataGrid\Mutator\MutatorInterface>; however, Zend\ServiceManager\AbstractPluginManager::get() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
379
        }
380
        $this->mutators[] = $mutator;
381
        return $this;
382
    }
383
384
    /**
385
     * Возвращвет верхнюю навигационную панель
386
     * @return NavigationBarInterface
387
     */
388
    public function getTopNavigationBar()
389
    {
390
        return $this->topNavigationBar;
391
    }
392
393
    /**
394
     * Устанавливает верхнюю навигационную панель
395
     * @param NavigationBarInterface $topNavigationBar
396
     * @return $this
397
     */
398
    public function setTopNavigationBar($topNavigationBar)
399
    {
400
        $this->topNavigationBar = $topNavigationBar;
401
        return $this;
402
    }
403
404
    /**
405
     * Возвращвет верхнюю навигационную панель
406
     * @return NavigationBarInterface
407
     */
408
    public function getBottomNavigationBar()
409
    {
410
        return $this->bottomNavigationBar;
411
    }
412
413
    /**
414
     * Устанавливает верхнюю навигационную панель
415
     * @param NavigationBarInterface $bottomNavigationBar
416
     * @return $this
417
     */
418
    public function setBottomNavigationBar($bottomNavigationBar)
419
    {
420
        $this->bottomNavigationBar = $bottomNavigationBar;
421
        return $this;
422
    }
423
    /**
424
     * Функция инициализации колонок
425
     * @return void
426
     */
427
    abstract public function init();
428
429
    /**
430
     * Возвращает массив строк
431
     * @return array
432
     */
433
    abstract public function getRowSet();
434
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
435