Passed
Push — master ( 421eba...09fd73 )
by Alexis
03:20 queued 11s
created

QueryCounter::checkQueryCount()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0261
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("Allowed amount of queries ($maxQueryCount) exceeded (actual: $actualQueryCount).");
44
        }
45 3
    }
46
47 5
    private function getMaxQueryCount(): ?int
48
    {
49 5
        $maxQueryCount = $this->getMaxQueryAnnotation();
50
51 5
        if (null !== $maxQueryCount) {
52 1
            return $maxQueryCount;
53
        }
54
55 4
        return $this->defaultMaxCount;
56
    }
57
58 5
    private function getMaxQueryAnnotation(): ?int
59
    {
60 5
        foreach (debug_backtrace() as $step) {
61 5
            if ('test' === substr($step['function'], 0, 4)) { //TODO: handle tests with the @test annotation
62 5
                $annotations = $this->annotationReader->getMethodAnnotations(
63 5
                    new \ReflectionMethod($step['class'], $step['function'])
64
                );
65
66 5
                foreach ($annotations as $annotationClass) {
67 1
                    if ($annotationClass instanceof QueryCount && isset($annotationClass->maxQueries)) {
68
                        /* @var $annotations \Liip\FunctionalTestBundle\Annotations\QueryCount */
69
70 5
                        return $annotationClass->maxQueries;
71
                    }
72
                }
73
            }
74
        }
75
76 4
        return null;
77
    }
78
}
79