Passed
Pull Request — master (#55)
by Thomas
01:32
created

Result::getEntities()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace ORM\Testing\EntityFetcherMock;
4
5
use ORM\Entity;
6
use ORM\EntityFetcher;
7
use ORM\QueryBuilder\QueryBuilder;
8
9
class Result extends EntityFetcher
10
{
11
    /** @var Entity[] */
12
    protected $entities = [];
13
14
    /** @var string[] */
15
    protected $regularExpressions = [];
16
17
    /**
18
     * Check if $fetcher matches the current query
19
     *
20
     * Returns the score for the given EntityFetcher. The more conditions match the higher the score:
21
     * - 0 = the query does not match one of the conditions
22
     * - 1 = no conditions required to match the query
23
     * - n = n-1 conditions matched the query
24
     *
25
     * @param EntityFetcher $fetcher
26
     * @return int
27
     */
28
    public function compare(EntityFetcher $fetcher)
29
    {
30
        $result = 1;
31
32
        foreach (['joins', 'where', 'groupBy', 'orderBy'] as $attribute) {
33
            foreach ($this->$attribute as $condition) {
34
                if (!in_array($condition, $fetcher->$attribute)) {
35
                    return 0;
36
                }
37
                $result++;
38
            }
39
        }
40
41
        // check if limit and offset matches
42
        if ($this->limit) {
43
            if ($this->limit !== $fetcher->limit || $this->offset !== $fetcher->offset) {
44
                return 0;
45
            }
46
            $result++;
47
        }
48
49
        // check if regular expressions match
50
        foreach ($this->regularExpressions as $expression) {
51
            if (!preg_match($expression, $fetcher->getQuery())) {
52
                return 0;
53
            }
54
            $result++;
55
        }
56
57
        return $result;
58
    }
59
60
    /**
61
     * Add a regular expression that has to match
62
     *
63
     * @param string $expression
64
     * @return $this
65
     * @codeCoverageIgnore trivial code
66
     */
67
    public function matches($expression)
68
    {
69
        $this->regularExpressions[] = $expression;
70
        return $this;
71
    }
72
73
    /**
74
     * Add entities to the result
75
     *
76
     * @param Entity ...$entities
77
     * @return $this
78
     * @codeCoverageIgnore trivial code
79
     */
80
    public function addEntities(Entity ...$entities)
81
    {
82
        array_push($this->entities, ...$entities);
83
        return $this;
84
    }
85
86
    /**
87
     * Get the entites for this result
88
     *
89
     * @return Entity[]
90
     * @codeCoverageIgnore trivial code
91
     */
92
    public function getEntities()
93
    {
94
        return $this->entities;
95
    }
96
}
97