|
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
|
|
|
|
|
11
|
|
|
class BasicQuery implements CollectionQueryInterface |
|
12
|
|
|
{ |
|
13
|
|
|
use ResolvesPropertyValueTrait; |
|
14
|
|
|
|
|
15
|
|
|
protected OperationProviderInterface $operationProvider; |
|
16
|
|
|
|
|
17
|
|
|
protected string $operator; |
|
18
|
|
|
|
|
19
|
|
|
protected $value; |
|
20
|
|
|
|
|
21
|
45 |
|
public function __construct( |
|
22
|
|
|
PropertyResolverInterface $propertyResolver, |
|
23
|
|
|
string $property, |
|
24
|
|
|
string $operator, |
|
25
|
|
|
$value, |
|
26
|
|
|
OperationProviderInterface $operationProvider = null |
|
27
|
|
|
) { |
|
28
|
45 |
|
$this->propertyResolver = $propertyResolver; |
|
29
|
45 |
|
$this->property = $property; |
|
30
|
45 |
|
$this->operator = $operator; |
|
31
|
45 |
|
$this->value = $value; |
|
32
|
|
|
|
|
33
|
45 |
|
$this->operationProvider = $operationProvider ?? new Operations(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
45 |
|
public function query(array $items): array |
|
37
|
|
|
{ |
|
38
|
45 |
|
return $this->filter($this->getFiltrationCallback(), $items); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
45 |
|
protected function filter(callable $callback, array $items): array |
|
42
|
|
|
{ |
|
43
|
45 |
|
return array_values(array_filter($items, $callback)); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
45 |
|
protected function getFiltrationCallback(): callable |
|
47
|
|
|
{ |
|
48
|
45 |
|
return fn ($item) => $this->itemMeetsCriteria($this->resolveValue($item)); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
45 |
|
protected function itemMeetsCriteria($value): bool |
|
52
|
|
|
{ |
|
53
|
45 |
|
return $this->operationProvider->operate($value, $this->operator, $this->value); |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|