CyclomaticComplexityAssessor::init()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 14
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Churn\Assessor;
6
7
/**
8
 * @internal
9
 */
10
final class CyclomaticComplexityAssessor implements Assessor
11
{
12
    /**
13
     * @var array<int, int>
14
     */
15
    private $tokens = [
16
        \T_BOOLEAN_AND => 1,
17
        \T_BOOLEAN_OR => 1,
18
        \T_CASE => 1,
19
        \T_CATCH => 1,
20
        \T_CLASS => 1,
21
        \T_COALESCE => 1,
22
        \T_ELSEIF => 1,
23
        \T_FOR => 1,
24
        \T_FOREACH => 1,
25
        \T_IF => 1,
26
        \T_INTERFACE => 1,
27
        \T_LOGICAL_AND => 1,
28
        \T_LOGICAL_OR => 1,
29
        \T_TRAIT => 1,
30
        \T_WHILE => 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
    #[\Override]
47
    public function assess(string $contents): int
48
    {
49
        $score = 0;
50
        foreach (\token_get_all($contents) as $token) {
51
            $score += $this->getComplexity($token[0]);
52
        }
53
54
        return \max(1, $score);
55
    }
56
57
    /**
58
     * Add missing tokens depending on the PHP version.
59
     */
60
    private function init(): void
61
    {
62
        $tokens = [
63
            // Since PHP 7.4
64
            'T_COALESCE_EQUAL',
65
            // Since PHP 8.1
66
            'T_ENUM',
67
        ];
68
        foreach ($tokens as $token) {
69
            if (!\defined($token)) {
70
                continue;
71
            }
72
73
            $this->tokens[(int) \constant($token)] = 1;
74
        }
75
    }
76
77
    /**
78
     * @param integer|string $code Code of a PHP token.
79
     */
80
    private function getComplexity($code): int
81
    {
82
        if ('?' === $code) {
83
            return 1;
84
        }
85
86
        return $this->tokens[$code] ?? 0;
87
    }
88
}
89