Completed
Pull Request — master (#389)
by
unknown
02:00
created

HalsteadVisitor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Hal\Metric\Class_\Text;
4
5
use Hal\Metric\FunctionMetric;
6
use Hal\Metric\Metrics;
7
use Hoa\Ruler\Model\Bag\Scalar;
8
use PhpParser\Node;
9
use PhpParser\Node\Stmt;
10
use PhpParser\NodeVisitorAbstract;
11
12
/**
13
 * Calculates Halstead complexity
14
 *
15
 *      According Wikipedia, "Halstead complexity measures are software metrics introduced by Maurice Howard Halstead in
16
 *      1977 as part of his treatise on establishing an empirical science of software development.
17
 *      Halstead makes the observation that metrics of the software should reflect the implementation or
18
 *      expression of algorithms in different languages, but be independent of their execution on a specific platform.
19
 *      These metrics are therefore computed statically from the code."
20
 *
21
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
22
 * Class HalsteadVisitor
23
 * @package Hal\Metric\Class_\Coupling
24
 */
25
class HalsteadVisitor extends NodeVisitorAbstract
26
{
27
28
    /**
29
     * @var Metrics
30
     */
31
    private $metrics;
32
33
    /**
34
     * ClassEnumVisitor constructor.
35
     * @param Metrics $metrics
36
     */
37
    public function __construct(Metrics $metrics)
38
    {
39
        $this->metrics = $metrics;
40
    }
41
42
    /**
43
     * @inheritdoc
44
     */
45
    public function leaveNode(Node $node)
46
    {
47
        if ($node instanceof Stmt\Class_ || $node instanceof Stmt\Function_ || $node instanceof Stmt\Trait_) {
48 View Code Duplication
            if ($node instanceof Stmt\Class_ || $node instanceof Stmt\Trait_) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
49
                $name = (string) (isset($node->namespacedName) ? $node->namespacedName : 'anonymous@'.spl_object_hash($node));
50
                $classOrFunction = $this->metrics->get($name);
51
            } else {
52
                $classOrFunction = new FunctionMetric((string) $node->name);
53
                $this->metrics->attach($classOrFunction);
54
            }
55
56
            // search for operands and operators
57
            $operands = [];
58
            $operators = [];
59
60
            iterate_over_node($node, function ($node) use (&$operators, &$operands) {
61
62
                if ($node instanceof Node\Expr\BinaryOp
63
                    || $node instanceof Node\Expr\AssignOp
64
                    || $node instanceof Stmt\If_
65
                    || $node instanceof Stmt\For_
66
                    || $node instanceof Stmt\Switch_
67
                    || $node instanceof Stmt\Catch_
68
                    || $node instanceof Stmt\Return_
69
                    || $node instanceof Stmt\While_
70
                    || $node instanceof Node\Expr\Assign
71
                ) {
72
                    // operators
73
                    array_push($operators, get_class($node));
74
                }
75
76
                // nicik/php-parser:^4
77
                if ($node instanceof Node\Param
78
                    && isset($node->var)
79
                    && $node->var instanceof Node\Expr\Variable
80
                ) {
81
                    return;
82
                }
83
84
                if ($node instanceof Node\Expr\Cast
85
                    || $node instanceof Node\Expr\Variable
86
                    || $node instanceof Node\Param
87
                    || $node instanceof Node\Scalar
88
                ) {
89
                    // operands
90
                    if (isset($node->value)) {
91
                        $name = $node->value;
92
                    } elseif (isset($node->name)) {
93
                        $name = $node->name;
94
                    } else {
95
                        $name = get_class($node);
96
                    }
97
                    array_push($operands, $name);
98
                }
99
            });
100
101
            // calculate halstead metrics
102
            $uniqueOperators = array_map('unserialize', array_unique(array_map('serialize', $operators)));
103
            $uniqueOperands = array_map('unserialize', array_unique(array_map('serialize', $operands)));
104
105
            $n1 = count($uniqueOperators, COUNT_NORMAL);
106
            $n2 = count($uniqueOperands, COUNT_NORMAL);
107
            $N1 = count($operators, COUNT_NORMAL);
108
            $N2 = count($operands, COUNT_NORMAL);
109
110
            if (($n2 == 0) || ($N2 == 0)) {
111
                // files without operators
112
                $V = $n1 = $n2 = $N1 = $N2 = $E = $D = $B = $T = $I = $L = 0;
113
            } else {
114
                $devAbility = 3000;
115
                $N = $N1 + $N2;
116
                $n = $n1 + $n2;
117
                $V = $N * log($n, 2);
118
                $L = (2 / max(1, $n1)) * ($n2 / $N2);
119
                $D = ($n1 / 2) * ($N2 / $n2);
120
                $E = $V * $D;
121
                $B = $V / $devAbility;
122
                $T = $E / 18;
123
                $I = $L * $V;
124
            }
125
126
            // save result
127
            $classOrFunction
128
                ->set('length', $N1 + $N2)
129
                ->set('vocabulary', $n1 + $n2)
130
                ->set('volume', round($V, 2))
131
                ->set('difficulty', round($D, 2))
132
                ->set('effort', round($E, 2))
133
                ->set('level', round($L, 2))
134
                ->set('bugs', round($B, 2))
135
                ->set('time', round($T))
136
                ->set('intelligentContent', round($I, 2))
137
                ->set('number_operators', $N1)
138
                ->set('number_operands', $N2)
139
                ->set('number_operators_unique', $n1)
140
                ->set('number_operands_unique', $n2);
141
            $this->metrics->attach($classOrFunction);
0 ignored issues
show
Bug introduced by
It seems like $classOrFunction defined by $this->metrics->get($name) on line 50 can be null; however, Hal\Metric\Metrics::attach() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
142
        }
143
    }
144
}
145