Passed
Push — master ( 7b0e14...a8dbbf )
by Fabien
01:54
created

CyclomaticComplexityAssessor::getComplexity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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
        $score = 0;
49
        foreach (\token_get_all($contents) as $token) {
50
            $score += $this->getComplexity($token[0]);
51
        }
52
53
        return \max(1, $score);
54
    }
55
56
    /**
57
     * Add missing tokens depending on the PHP version.
58
     */
59
    private function init(): void
60
    {
61
        $tokens = [
62
            // Since PHP 7.4
63
            'T_COALESCE_EQUAL',
64
            // Since PHP 8.1
65
            'T_ENUM',
66
        ];
67
        foreach ($tokens as $token) {
68
            if (!\defined($token)) {
69
                continue;
70
            }
71
72
            $this->tokens[(int) \constant($token)] = 1;
73
        }
74
    }
75
76
    /**
77
     * @param integer|string $code Code of a PHP token.
78
     */
79
    private function getComplexity($code): int
80
    {
81
        if ('?' === $code) {
82
            return 1;
83
        }
84
85
        return $this->tokens[$code] ?? 0;
86
    }
87
}
88