Test Failed
Push — master ( d3f723...421eba )
by Alexis
02:13 queued 14s
created

QueryCounter::getMaxQueryAnnotation()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 16
cp 0
rs 8.9777
c 0
b 0
f 0
cc 6
nc 5
nop 0
crap 42
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Liip/FunctionalTestBundle
7
 *
8
 * (c) Lukas Kahwe Smith <[email protected]>
9
 *
10
 * This source file is subject to the MIT license that is bundled
11
 * with this source code in the file LICENSE.
12
 */
13
14
namespace Liip\FunctionalTestBundle;
15
16
use Doctrine\Common\Annotations\Reader;
17
use Liip\FunctionalTestBundle\Annotations\QueryCount;
18
use Liip\FunctionalTestBundle\Exception\AllowedQueriesExceededException;
19
20
final class QueryCounter
21
{
22
    /** @var int */
23
    private $defaultMaxCount;
24
25
    /** @var Reader */
26
    private $annotationReader;
27
28
    public function __construct(?int $defaultMaxCount, Reader $annotationReader)
29
    {
30
        $this->defaultMaxCount = $defaultMaxCount;
31
        $this->annotationReader = $annotationReader;
32
    }
33
34
    public function checkQueryCount(int $actualQueryCount): void
35
    {
36
        $maxQueryCount = $this->getMaxQueryCount();
37
38
        if (null === $maxQueryCount) {
39
            return;
40
        }
41
42
        if ($actualQueryCount > $maxQueryCount) {
43
            throw new AllowedQueriesExceededException(
44
                "Allowed amount of queries ($maxQueryCount) exceeded (actual: $actualQueryCount)."
45
            );
46
        }
47
    }
48
49
    private function getMaxQueryCount(): ?int
50
    {
51
        $maxQueryCount = $this->getMaxQueryAnnotation();
52
53
        if (null !== $maxQueryCount) {
54
            return $maxQueryCount;
55
        }
56
57
        return $this->defaultMaxCount;
58
    }
59
60
    private function getMaxQueryAnnotation(): ?int
61
    {
62
        foreach (debug_backtrace() as $step) {
63
            if ('test' === substr($step['function'], 0, 4)) { //TODO: handle tests with the @test annotation
64
                $annotations = $this->annotationReader->getMethodAnnotations(
65
                    new \ReflectionMethod($step['class'], $step['function'])
66
                );
67
68
                foreach ($annotations as $annotationClass) {
69
                    if ($annotationClass instanceof QueryCount && isset($annotationClass->maxQueries)) {
70
                        /* @var $annotations \Liip\FunctionalTestBundle\Annotations\QueryCount */
71
72
                        return $annotationClass->maxQueries;
73
                    }
74
                }
75
            }
76
        }
77
78
        return null;
79
    }
80
}
81