Passed
Push — master ( 7dffb9...f06de2 )
by Alexander
02:41 queued 10s
created

GroupFilter::withFiltersArray()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7.3329

Importance

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