Passed
Push — master ( 951d77...1f27ac )
by Alexander
02:35
created

Group::withFiltersArray()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 5
nop 1
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Data\Reader\Filter;
6
7
use InvalidArgumentException;
8
9
use function array_shift;
10
use function is_array;
11
use function is_string;
12
use function sprintf;
13
14
abstract class Group implements FilterInterface
15
{
16
    /**
17
     * @var array[]|FilterInterface[]
18
     */
19
    private array $filters;
20
21 32
    public function __construct(FilterInterface ...$filters)
22
    {
23 32
        $this->filters = $filters;
24
    }
25
26 6
    public function toArray(): array
27
    {
28 6
        $filtersArray = [];
29
30 6
        foreach ($this->filters as $filter) {
31 6
            if ($filter instanceof FilterInterface) {
32 6
                $filter = $filter->toArray();
33
            }
34
35 6
            $filtersArray[] = $filter;
36
        }
37
38 6
        return [static::getOperator(), $filtersArray];
39
    }
40
41
    /**
42
     * Building criteria with array.
43
     *
44
     * ```php
45
     * $dataReader->withFilter((new All())->withFiltersArray(
46
     *   [
47
     *     ['>', 'id', 88],
48
     *     ['or', [
49
     *        ['=', 'state', 2],
50
     *        ['like', 'name', 'eva'],
51
     *     ],
52
     *   ]
53
     * ));
54
     * ```
55
     *
56
     * @param array[]|FilterInterface[] $filtersArray
57
     *
58
     * @return static
59
     *
60
     * @psalm-suppress DocblockTypeContradiction
61
     */
62 28
    public function withFiltersArray(array $filtersArray): self
63
    {
64 28
        foreach ($filtersArray as $key => $filter) {
65 28
            if ($filter instanceof FilterInterface) {
66 14
                continue;
67
            }
68
69 28
            if (!is_array($filter)) {
70 12
                throw new InvalidArgumentException(sprintf('Invalid filter on "%s" key.', $key));
71
            }
72
73 16
            $operator = array_shift($filter);
74
75 16
            if (!is_string($operator) || $operator === '') {
76 14
                throw new InvalidArgumentException(sprintf('Invalid filter operator on "%s" key.', $key));
77
            }
78
        }
79
80 2
        $new = clone $this;
81 2
        $new->filters = $filtersArray;
82 2
        return $new;
83
    }
84
}
85