Test Failed
Push — master ( 6eea59...bfd094 )
by Chris
31:05
created

Operations   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 88.46%

Importance

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

4 Methods

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