Completed
Push — master ( df9952...f86661 )
by Hannes
04:17 queued 02:11
created

Doc::evaluate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace hanneskod\yaysondb\Expression;
6
7
use hanneskod\yaysondb\Exception\RuntimeException;
8
9
/**
10
 * Evaluate documents and nested subdocuments
11
 */
12
class Doc implements ExpressionInterface
13
{
14
    /**
15
     * @var \Closure[] List of expressions
16
     */
17
    private $exprs = [];
18
19
    /**
20
     * Create from query document
21
     *
22
     * @param array $query
23
     */
24
    public function __construct(array $query)
25
    {
26
        /** @var ExpressionInterface $expr */
27
        foreach ($query as $key => $expr) {
28
            if (!$expr instanceof ExpressionInterface) {
29
                throw new RuntimeException(
30
                    "Query operator must implement ExpressionInterface, found: ".gettype($expr)
31
                );
32
            }
33
34
            $this->exprs[] = function (array $doc) use ($key, $expr) {
35
                return isset($doc[$key]) && $expr->evaluate($doc[$key]);
36
            };
37
        }
38
    }
39
40
    public function evaluate($doc): bool
41
    {
42
        if (!is_array($doc)) {
43
            return false;
44
        }
45
46
        /** @var \Closure $exp */
47
        foreach ($this->exprs as $exp) {
48
            if (!$exp($doc)) {
49
                return false;
50
            }
51
        }
52
53
        return true;
54
    }
55
}
56