|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace WebTheory\Collection\Query; |
|
4
|
|
|
|
|
5
|
|
|
use WebTheory\Collection\Contracts\CollectionQueryInterface; |
|
6
|
|
|
use WebTheory\Collection\Contracts\OperationProviderInterface; |
|
7
|
|
|
use WebTheory\Collection\Contracts\PropertyResolverInterface; |
|
8
|
|
|
use WebTheory\Collection\Query\Operation\Operations; |
|
9
|
|
|
use WebTheory\Collection\Resolution\Abstracts\ResolvesPropertyValueTrait; |
|
10
|
|
|
use WebTheory\Collection\Resolution\PropertyResolver; |
|
11
|
|
|
|
|
12
|
|
|
class BasicQuery implements CollectionQueryInterface |
|
13
|
|
|
{ |
|
14
|
|
|
use ResolvesPropertyValueTrait; |
|
15
|
|
|
|
|
16
|
|
|
protected OperationProviderInterface $operationProvider; |
|
17
|
|
|
|
|
18
|
|
|
protected string $operator; |
|
19
|
|
|
|
|
20
|
|
|
protected $value; |
|
21
|
|
|
|
|
22
|
20 |
|
public function __construct( |
|
23
|
|
|
string $property, |
|
24
|
|
|
string $operator, |
|
25
|
|
|
$value, |
|
26
|
|
|
?PropertyResolverInterface $propertyResolver = null, |
|
27
|
|
|
?OperationProviderInterface $operationProvider = null |
|
28
|
|
|
) { |
|
29
|
20 |
|
$this->property = $property; |
|
30
|
20 |
|
$this->operator = $operator; |
|
31
|
20 |
|
$this->value = $value; |
|
32
|
|
|
|
|
33
|
20 |
|
$this->propertyResolver = $propertyResolver ?? new PropertyResolver(); |
|
34
|
20 |
|
$this->operationProvider = $operationProvider ?? new Operations(); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
12 |
|
public function query(array $items): array |
|
38
|
|
|
{ |
|
39
|
12 |
|
return array_filter($items, [$this, 'itemMeetsCriteria']); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
8 |
|
public function first(array $items): ?object |
|
43
|
|
|
{ |
|
44
|
8 |
|
foreach ($items as $item) { |
|
45
|
8 |
|
if ($this->itemMeetsCriteria($item)) { |
|
46
|
7 |
|
return $item; |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
1 |
|
return null; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
2 |
|
public function match(array $items): bool |
|
54
|
|
|
{ |
|
55
|
2 |
|
return is_object($this->first($items)); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
20 |
|
protected function itemMeetsCriteria(object $item): bool |
|
59
|
|
|
{ |
|
60
|
20 |
|
return $this->propertyIsMatch($this->resolveValue($item)); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
20 |
|
protected function propertyIsMatch($value): bool |
|
64
|
|
|
{ |
|
65
|
20 |
|
return $this->operationProvider->operate( |
|
66
|
20 |
|
$value, |
|
67
|
20 |
|
$this->operator, |
|
68
|
20 |
|
$this->value |
|
69
|
20 |
|
); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|