1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebTheory\Collection\Query; |
4
|
|
|
|
5
|
|
|
use LogicException; |
6
|
|
|
use WebTheory\Collection\Contracts\CollectionQueryInterface; |
7
|
|
|
use WebTheory\Collection\Contracts\PropertyResolverInterface; |
8
|
|
|
use WebTheory\Collection\Resolution\Abstracts\ResolvesPropertyValueTrait; |
9
|
|
|
|
10
|
|
|
class BasicQuery implements CollectionQueryInterface |
11
|
|
|
{ |
12
|
|
|
use ResolvesPropertyValueTrait; |
13
|
|
|
|
14
|
|
|
protected string $operator; |
15
|
|
|
|
16
|
|
|
protected $value; |
17
|
|
|
|
18
|
21 |
|
public function __construct(PropertyResolverInterface $propertyResolver, string $property, string $operator, $value) |
19
|
|
|
{ |
20
|
21 |
|
$this->propertyResolver = $propertyResolver; |
21
|
21 |
|
$this->property = $property; |
22
|
21 |
|
$this->operator = $operator; |
23
|
21 |
|
$this->value = $value; |
24
|
|
|
} |
25
|
|
|
|
26
|
21 |
|
public function query(array $items): array |
27
|
|
|
{ |
28
|
21 |
|
return $this->filter($this->getFiltrationCallback(), $items); |
29
|
|
|
} |
30
|
|
|
|
31
|
21 |
|
protected function filter(callable $callback, array $items): array |
32
|
|
|
{ |
33
|
21 |
|
return array_values(array_filter($items, $callback)); |
34
|
|
|
} |
35
|
|
|
|
36
|
21 |
|
protected function getFiltrationCallback(): callable |
37
|
|
|
{ |
38
|
21 |
|
return fn ($item) => $this->itemMeetsCriteria( |
39
|
21 |
|
$this->resolveValue($item), |
40
|
21 |
|
$this->operator, |
41
|
21 |
|
$this->value |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
21 |
|
protected function itemMeetsCriteria($value, string $operator, $comparedTo): bool |
46
|
|
|
{ |
47
|
21 |
|
switch ($operator) { |
48
|
21 |
|
case '=': |
49
|
18 |
|
return $value === $comparedTo; |
50
|
|
|
|
51
|
3 |
|
case '!=': |
52
|
|
|
return $value !== $comparedTo; |
53
|
|
|
|
54
|
3 |
|
case '>': |
55
|
|
|
return $value > $comparedTo; |
56
|
|
|
|
57
|
3 |
|
case '<': |
58
|
|
|
return $value < $comparedTo; |
59
|
|
|
|
60
|
3 |
|
case '>=': |
61
|
|
|
return $value >= $comparedTo; |
62
|
|
|
|
63
|
3 |
|
case '<=': |
64
|
|
|
return $value <= $comparedTo; |
65
|
|
|
|
66
|
3 |
|
case 'in': |
67
|
|
|
return in_array($value, $comparedTo); |
68
|
|
|
|
69
|
3 |
|
case 'not in': |
70
|
3 |
|
return !in_array($value, $comparedTo); |
71
|
|
|
|
72
|
|
|
default: |
73
|
|
|
throw new LogicException( |
74
|
|
|
"Querying by operator \"{$operator}\" is not supported." |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|