1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebTheory\Collection\Query\Operation; |
4
|
|
|
|
5
|
|
|
use LogicException; |
6
|
|
|
use WebTheory\Collection\Contracts\OperationProviderInterface; |
7
|
|
|
|
8
|
|
|
class Operations implements OperationProviderInterface |
9
|
|
|
{ |
10
|
|
|
protected array $operators; |
11
|
|
|
|
12
|
165 |
|
public function __construct(array $operators = []) |
13
|
|
|
{ |
14
|
165 |
|
$this->operators = $operators + $this->defaultOperators(); |
15
|
|
|
} |
16
|
|
|
|
17
|
45 |
|
public function operate($value1, string $operator, $value2): bool |
18
|
|
|
{ |
19
|
45 |
|
$operator = $this->getOperator($operator); |
20
|
|
|
|
21
|
45 |
|
return $operator($value1, $value2); |
22
|
|
|
} |
23
|
|
|
|
24
|
45 |
|
protected function getOperator(string $operator): callable |
25
|
|
|
{ |
26
|
45 |
|
if ($resolved = $this->operators[$operator] ?? false) { |
27
|
45 |
|
return $resolved; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
throw new LogicException( |
31
|
|
|
"Querying by operator \"{$operator}\" is not supported." |
32
|
|
|
); |
33
|
|
|
} |
34
|
|
|
|
35
|
165 |
|
protected function defaultOperators(): array |
36
|
|
|
{ |
37
|
|
|
return [ |
38
|
165 |
|
'=' => fn ($a, $b): bool => $a === $b, |
39
|
|
|
|
40
|
165 |
|
'!=' => fn ($a, $b): bool => $a !== $b, |
41
|
|
|
|
42
|
165 |
|
'>' => fn ($a, $b): bool => $a > $b, |
43
|
|
|
|
44
|
165 |
|
'<' => fn ($a, $b): bool => $a < $b, |
45
|
|
|
|
46
|
165 |
|
'>=' => fn ($a, $b): bool => $a >= $b, |
47
|
|
|
|
48
|
165 |
|
'<=' => fn ($a, $b): bool => $a <= $b, |
49
|
|
|
|
50
|
165 |
|
'in' => fn ($a, $b): bool => in_array($a, $b), |
51
|
|
|
|
52
|
165 |
|
'not in' => fn ($a, $b): bool => !in_array($a, $b), |
53
|
|
|
|
54
|
165 |
|
'like' => fn ($a, $b): bool => $a == $b, |
55
|
|
|
|
56
|
165 |
|
'not like' => fn ($a, $b): bool => $a != $b, |
57
|
|
|
|
58
|
165 |
|
'between' => fn ($a, $b): bool => $a >= $b[0] && $a <= $b[1], |
59
|
|
|
|
60
|
165 |
|
'not between' => fn ($a, $b): bool => $a < $b[0] || $a > $b[1], |
61
|
|
|
]; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|