1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Data\Reader\Iterable\Processor; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Yiisoft\Data\Reader\Filter\FilterProcessorInterface; |
9
|
|
|
use Yiisoft\Data\Reader\FilterDataValidationHelper; |
10
|
|
|
|
11
|
|
|
use function array_shift; |
12
|
|
|
use function count; |
13
|
|
|
use function is_array; |
14
|
|
|
use function is_string; |
15
|
|
|
use function sprintf; |
16
|
|
|
|
17
|
|
|
abstract class GroupProcessor implements IterableProcessorInterface, FilterProcessorInterface |
18
|
|
|
{ |
19
|
|
|
abstract protected function checkResults(array $results): bool; |
20
|
|
|
|
21
|
73 |
|
public function match(array $item, array $arguments, array $filterProcessors): bool |
22
|
|
|
{ |
23
|
73 |
|
if (count($arguments) !== 1) { |
24
|
8 |
|
throw new InvalidArgumentException('$arguments should contain exactly one element.'); |
25
|
|
|
} |
26
|
|
|
|
27
|
65 |
|
[$subFilters] = $arguments; |
28
|
|
|
|
29
|
65 |
|
if (!is_array($subFilters)) { |
30
|
16 |
|
throw new InvalidArgumentException(sprintf( |
31
|
16 |
|
'The sub filters should be array. The %s is received.', |
32
|
16 |
|
FilterDataValidationHelper::getValueType($subFilters), |
33
|
|
|
)); |
34
|
|
|
} |
35
|
|
|
|
36
|
49 |
|
$results = []; |
37
|
|
|
|
38
|
49 |
|
foreach ($subFilters as $subFilter) { |
39
|
49 |
|
if (!is_array($subFilter)) { |
40
|
16 |
|
throw new InvalidArgumentException(sprintf( |
41
|
16 |
|
'The sub filter should be array. The %s is received.', |
42
|
16 |
|
FilterDataValidationHelper::getValueType($subFilter), |
43
|
|
|
)); |
44
|
|
|
} |
45
|
|
|
|
46
|
33 |
|
if (empty($subFilter)) { |
47
|
2 |
|
throw new InvalidArgumentException('At least operator should be provided.'); |
48
|
|
|
} |
49
|
|
|
|
50
|
31 |
|
$operator = array_shift($subFilter); |
51
|
|
|
|
52
|
31 |
|
if (!is_string($operator)) { |
53
|
10 |
|
throw new InvalidArgumentException(sprintf( |
54
|
10 |
|
'The operator should be string. The %s is received.', |
55
|
10 |
|
FilterDataValidationHelper::getValueType($operator), |
56
|
|
|
)); |
57
|
|
|
} |
58
|
|
|
|
59
|
21 |
|
if ($operator === '') { |
60
|
2 |
|
throw new InvalidArgumentException('The operator string cannot be empty.'); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** @var IterableProcessorInterface|null $filterProcessor */ |
64
|
19 |
|
$filterProcessor = $filterProcessors[$operator] ?? null; |
65
|
|
|
|
66
|
19 |
|
if ($filterProcessor === null) { |
67
|
2 |
|
throw new InvalidArgumentException(sprintf('"%s" operator is not supported.', $operator)); |
68
|
|
|
} |
69
|
|
|
|
70
|
17 |
|
FilterDataValidationHelper::assertFilterProcessorIsIterable($filterProcessor); |
71
|
15 |
|
$results[] = $filterProcessor->match($item, $subFilter, $filterProcessors); |
72
|
|
|
} |
73
|
|
|
|
74
|
15 |
|
return $this->checkResults($results); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|