Completed
Push — master ( c6a5c1...3d4d4a )
by Alexis
08:07 queued 02:27
created

QueryCounter::checkQueryCount()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 8
cp 0.875
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0175
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 12
    public function __construct(?int $defaultMaxCount, Reader $annotationReader)
29
    {
30 12
        $this->defaultMaxCount = $defaultMaxCount;
31 12
        $this->annotationReader = $annotationReader;
32 12
    }
33
34 5
    public function checkQueryCount(int $actualQueryCount): void
35
    {
36 5
        $maxQueryCount = $this->getMaxQueryCount();
37
38 5
        if (null === $maxQueryCount) {
39
            return;
40
        }
41
42 5
        if ($actualQueryCount > $maxQueryCount) {
43 2
            throw new AllowedQueriesExceededException(
44 2
                "Allowed amount of queries ($maxQueryCount) exceeded (actual: $actualQueryCount)."
45
            );
46
        }
47 3
    }
48
49 5
    private function getMaxQueryCount(): ?int
50
    {
51 5
        $maxQueryCount = $this->getMaxQueryAnnotation();
52
53 5
        if (null !== $maxQueryCount) {
54 1
            return $maxQueryCount;
55
        }
56
57 4
        return $this->defaultMaxCount;
58
    }
59
60 5
    private function getMaxQueryAnnotation(): ?int
61
    {
62 5
        foreach (debug_backtrace() as $step) {
63 5
            if ('test' === substr($step['function'], 0, 4)) { //TODO: handle tests with the @test annotation
64 5
                $annotations = $this->annotationReader->getMethodAnnotations(
65 5
                    new \ReflectionMethod($step['class'], $step['function'])
66
                );
67
68 5
                foreach ($annotations as $annotationClass) {
69 1
                    if ($annotationClass instanceof QueryCount && isset($annotationClass->maxQueries)) {
70
                        /* @var $annotations \Liip\FunctionalTestBundle\Annotations\QueryCount */
71
72 5
                        return $annotationClass->maxQueries;
73
                    }
74
                }
75
            }
76
        }
77
78 4
        return null;
79
    }
80
}
81