Completed
Push — master ( 1af926...5d5b5a )
by
unknown
05:35 queued 04:17
created

HalsteadVisitor::leaveNode()   D

Complexity

Conditions 27
Paths 7

Size

Total Lines 99

Duplication

Lines 7
Ratio 7.07 %

Importance

Changes 0
Metric Value
cc 27
nc 7
nop 1
dl 7
loc 99
rs 4.1666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * @package Hal\Metric\Class_\Coupling
23
 */
24
class HalsteadVisitor extends NodeVisitorAbstract
25
{
26
27
    /**
28
     * @var Metrics
29
     */
30
    private $metrics;
31
32
    /**
33
     * @param Metrics $metrics
34
     */
35
    public function __construct(Metrics $metrics)
36
    {
37
        $this->metrics = $metrics;
38
    }
39
40
    /**
41
     * @inheritdoc
42
     */
43
    public function leaveNode(Node $node)
44
    {
45
        if ($node instanceof Stmt\Class_ || $node instanceof Stmt\Function_ || $node instanceof Stmt\Trait_) {
46 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...
47
                $name = (string) (isset($node->namespacedName) ? $node->namespacedName : 'anonymous@'.spl_object_hash($node));
48
                $classOrFunction = $this->metrics->get($name);
49
            } else {
50
                $classOrFunction = new FunctionMetric((string) $node->name);
51
                $this->metrics->attach($classOrFunction);
52
            }
53
54
            // search for operands and operators
55
            $operands = [];
56
            $operators = [];
57
58
            iterate_over_node($node, function ($node) use (&$operators, &$operands) {
59
60
                if ($node instanceof Node\Expr\BinaryOp
61
                    || $node instanceof Node\Expr\AssignOp
62
                    || $node instanceof Stmt\If_
63
                    || $node instanceof Stmt\For_
64
                    || $node instanceof Stmt\Switch_
65
                    || $node instanceof Stmt\Catch_
66
                    || $node instanceof Stmt\Return_
67
                    || $node instanceof Stmt\While_
68
                    || $node instanceof Node\Expr\Assign
69
                ) {
70
                    // operators
71
                    array_push($operators, get_class($node));
72
                }
73
74
                // nicik/php-parser:^4
75
                if ($node instanceof Node\Param
76
                    && isset($node->var)
77
                    && $node->var instanceof Node\Expr\Variable
78
                ) {
79
                    return;
80
                }
81
82
                if ($node instanceof Node\Expr\Cast
83
                    || $node instanceof Node\Expr\Variable
84
                    || $node instanceof Node\Param
85
                    || $node instanceof Node\Scalar
86
                ) {
87
                    // operands
88
                    if (isset($node->value)) {
89
                        $name = $node->value;
90
                    } elseif (isset($node->name)) {
91
                        $name = $node->name;
92
                    } else {
93
                        $name = get_class($node);
94
                    }
95
                    array_push($operands, $name);
96
                }
97
            });
98
99
            // calculate halstead metrics
100
            $uniqueOperators = array_map('unserialize', array_unique(array_map('serialize', $operators)));
101
            $uniqueOperands = array_map('unserialize', array_unique(array_map('serialize', $operands)));
102
103
            $n1 = count($uniqueOperators, COUNT_NORMAL);
104
            $n2 = count($uniqueOperands, COUNT_NORMAL);
105
            $N1 = count($operators, COUNT_NORMAL);
106
            $N2 = count($operands, COUNT_NORMAL);
107
108
            if (($n2 == 0) || ($N2 == 0)) {
109
                // files without operators
110
                $V = $n1 = $n2 = $N1 = $N2 = $E = $D = $B = $T = $I = $L = 0;
111
            } else {
112
                $devAbility = 3000;
113
                $N = $N1 + $N2;
114
                $n = $n1 + $n2;
115
                $V = $N * log($n, 2);
116
                $L = (2 / max(1, $n1)) * ($n2 / $N2);
117
                $D = ($n1 / 2) * ($N2 / $n2);
118
                $E = $V * $D;
119
                $B = $V / $devAbility;
120
                $T = $E / 18;
121
                $I = $L * $V;
122
            }
123
124
            // save result
125
            $classOrFunction
126
                ->set('length', $N1 + $N2)
127
                ->set('vocabulary', $n1 + $n2)
128
                ->set('volume', round($V, 2))
129
                ->set('difficulty', round($D, 2))
130
                ->set('effort', round($E, 2))
131
                ->set('level', round($L, 2))
132
                ->set('bugs', round($B, 2))
133
                ->set('time', round($T))
134
                ->set('intelligentContent', round($I, 2))
135
                ->set('number_operators', $N1)
136
                ->set('number_operands', $N2)
137
                ->set('number_operators_unique', $n1)
138
                ->set('number_operands_unique', $n2);
139
            $this->metrics->attach($classOrFunction);
0 ignored issues
show
Bug introduced by
It seems like $classOrFunction defined by $this->metrics->get($name) on line 48 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...
140
        }
141
    }
142
}
143