Passed
Push — master ( 4f5a04...f7b3b1 )
by Chris
07:47
created

Operations   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 23
c 1
b 0
f 0
dl 0
loc 54
ccs 22
cts 24
cp 0.9167
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A defaultOperators() 0 26 3
A __construct() 0 4 2
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 192
    public function __construct(array $operators = [], bool $useDefaults = true)
13
    {
14 192
        $this->operators = $operators
15 192
            + ($useDefaults ? $this->defaultOperators() : []);
16
    }
17
18 27
    public function operate($value1, string $operator, $value2): bool
19
    {
20 27
        $operator = $this->getOperator($operator);
21
22 27
        return $operator($value1, $value2);
23
    }
24
25 27
    protected function getOperator(string $operator): callable
26
    {
27 27
        if ($resolved = $this->operators[$operator] ?? false) {
28 27
            return $resolved;
29
        }
30
31
        throw new LogicException(
32
            "Querying by operator \"{$operator}\" is not supported."
33
        );
34
    }
35
36 192
    protected function defaultOperators(): array
37
    {
38
        return [
39 192
            '=' => fn ($a, $b): bool => $a === $b,
40
41 192
            '!=' => fn ($a, $b): bool => $a !== $b,
42
43 192
            '>' => fn ($a, $b): bool => $a > $b,
44
45 192
            '<' => fn ($a, $b): bool => $a < $b,
46
47 192
            '>=' => fn ($a, $b): bool => $a >= $b,
48
49 192
            '<=' => fn ($a, $b): bool => $a <= $b,
50
51 192
            'in' => fn ($a, $b): bool => in_array($a, $b),
52
53 192
            'not in' => fn ($a, $b): bool => !in_array($a, $b),
54
55 192
            'like' => fn ($a, $b): bool => $a == $b,
56
57 192
            'not like' => fn ($a, $b): bool => $a != $b,
58
59 192
            'between' => fn ($a, $b): bool => $a >= $b[0] && $a <= $b[1],
60
61 192
            'not between' => fn ($a, $b): bool => $a < $b[0] || $a > $b[1],
62
        ];
63
    }
64
}
65