Passed
Pull Request — master (#351)
by Fabien
02:03
created

CyclomaticComplexityAssessor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Churn\Assessor;
6
7
/**
8
 * @internal
9
 */
10
class CyclomaticComplexityAssessor
11
{
12
    /**
13
     * @var array<int, int>
14
     */
15
    private $tokens = [
16
        \T_CLASS => 1,
17
        \T_INTERFACE => 1,
18
        \T_TRAIT => 1,
19
        \T_IF => 1,
20
        \T_ELSEIF => 1,
21
        \T_FOR => 1,
22
        \T_FOREACH => 1,
23
        \T_WHILE => 1,
24
        \T_CASE => 1,
25
        \T_CATCH => 1,
26
        \T_BOOLEAN_AND => 1,
27
        \T_LOGICAL_AND => 1,
28
        \T_BOOLEAN_OR => 1,
29
        \T_LOGICAL_OR => 1,
30
        \T_COALESCE => 1,
31
    ];
32
33
    /**
34
     * Class constructor.
35
     */
36
    public function __construct()
37
    {
38
        $this->init();
39
    }
40
41
    /**
42
     * Assess the files cyclomatic complexity.
43
     *
44
     * @param string $contents The contents of a PHP file.
45
     */
46
    public function assess(string $contents): int
47
    {
48
        $tokens = \token_get_all($contents);
49
        $score = 0;
50
        foreach ($tokens as $token) {
51
            if (\is_array($token)) {
52
                $score += $this->getComplexity($token[0]);
53
54
                continue;
55
            }
56
            if ('?' !== $token) {
57
                continue;
58
            }
59
60
            $score += 1;
61
        }
62
63
        return 0 === $score
0 ignored issues
show
introduced by
The condition 0 === $score is always true.
Loading history...
64
            ? 1
65
            : $score;
66
    }
67
68
    /**
69
     * Add missing tokens depending on the PHP version.
70
     */
71
    private function init(): void
72
    {
73
        $tokens = [
74
            // Since PHP 7.4
75
            'T_COALESCE_EQUAL',
76
            // Since PHP 8.1
77
            'T_ENUM',
78
        ];
79
        foreach ($tokens as $token) {
80
            if (!\defined($token)) {
81
                continue;
82
            }
83
84
            $this->tokens[(int) \constant($token)] = 1;
85
        }
86
    }
87
88
    /**
89
     * @param integer $code Code of a PHP token.
90
     */
91
    private function getComplexity(int $code): int
92
    {
93
        return $this->tokens[$code] ?? 0;
94
    }
95
}
96