Completed
Push — master ( e8aa43...f91003 )
by personal
19s queued 13s
created

McCabe::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * (c) Jean-François Lépine <https://twitter.com/Halleck45>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Hal\Metrics\Complexity\Component\McCabe;
11
use Hal\Component\Token\TokenCollection;
12
13
/**
14
 * Calculates cyclomatic complexity
15
 *
16
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
17
 */
18
class McCabe {
19
20
    /**
21
     * Calculate cyclomatic complexity number
22
     *
23
     * We can calculate ccn in two ways (we choose the second):
24
     *
25
     *  1.  Cyclomatic complexity (CC) = E - N + 2P
26
     *      Where:
27
     *      P = number of disconnected parts of the flow graph (e.g. a calling program and a subroutine)
28
     *      E = number of edges (transfers of control)
29
     *      N = number of nodes (sequential group of statements containing only one transfer of control)
30
     *
31
     * 2. CC = Number of each decision point
32
     *
33
     * @param TokenCollection $tokens
34
     * @return Result
35
     */
36
    public function calculate($tokens)
37
    {
38
        $info = new Result;
39
40
        $ccn = 1; // default path
41
        foreach($tokens as $token) {
42
43
            switch($token->getType()) {
44
                case T_IF:
45
                case T_ELSEIF:
46
                case T_FOREACH:
47
                case T_FOR:
48
                case T_WHILE:
49
                case T_DO:
50
                case T_BOOLEAN_AND:
51
                case T_LOGICAL_AND:
52
                case T_BOOLEAN_OR:
53
                case T_LOGICAL_OR:
54
                case T_SPACESHIP:
55
                case T_CASE:
56
                case T_DEFAULT:
57
                case T_CATCH:
58
                case T_CONTINUE:
59
                    $ccn++;
60
                    break;
61
                case T_STRING:
62
                    if('?' == $token->getValue()) {
63
                        $ccn = $ccn + 2;
64
                    }
65
                    break;
66
                case T_COALESCE:
67
                    $ccn = $ccn + 2;
68
                    break;
69
            }
70
71
        }
72
73
        $info->setCyclomaticComplexityNumber(max(1, $ccn));
74
        return $info;
75
    }
76
}
77