Passed
Push — master ( 61a477...8a3759 )
by Chris
07:43
created

Operations   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 91.3%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 22
c 1
b 0
f 0
dl 0
loc 53
ccs 21
cts 23
cp 0.913
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A defaultOperators() 0 26 3
A __construct() 0 3 1
A operate() 0 5 1
A getOperator() 0 8 2
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