Passed
Branch master (69397d)
by Chris
07:22
created

BasicQuery   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 22
dl 0
loc 57
ccs 21
cts 21
cp 1
rs 10
c 1
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A query() 0 3 1
A __construct() 0 13 1
A match() 0 3 1
A itemMeetsCriteria() 0 3 1
A first() 0 9 3
A propertyIsMatch() 0 6 1
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
use WebTheory\Collection\Resolution\PropertyResolver;
11
12
class BasicQuery implements CollectionQueryInterface
13
{
14
    use ResolvesPropertyValueTrait;
15
16
    protected OperationProviderInterface $operationProvider;
17
18
    protected string $operator;
19
20
    protected $value;
21
22 33
    public function __construct(
23
        string $property,
24
        string $operator,
25
        $value,
26
        ?PropertyResolverInterface $propertyResolver = null,
27
        ?OperationProviderInterface $operationProvider = null
28
    ) {
29 33
        $this->property = $property;
30 33
        $this->operator = $operator;
31 33
        $this->value = $value;
32
33 33
        $this->propertyResolver = $propertyResolver ?? new PropertyResolver();
34 33
        $this->operationProvider = $operationProvider ?? new Operations();
35
    }
36
37 18
    public function query(array $items): array
38
    {
39 18
        return array_filter($items, [$this, 'itemMeetsCriteria']);
40
    }
41
42 15
    public function first(array $items): ?object
43
    {
44 15
        foreach ($items as $item) {
45 15
            if ($this->itemMeetsCriteria($item)) {
46 12
                return $item;
47
            }
48
        }
49
50 3
        return null;
51
    }
52
53 6
    public function match(array $items): bool
54
    {
55 6
        return is_object($this->first($items));
56
    }
57
58 33
    protected function itemMeetsCriteria(object $item): bool
59
    {
60 33
        return $this->propertyIsMatch($this->resolveValue($item));
61
    }
62
63 33
    protected function propertyIsMatch($value): bool
64
    {
65 33
        return $this->operationProvider->operate(
66
            $value,
67 33
            $this->operator,
68 33
            $this->value
69
        );
70
    }
71
}
72