Completed
Push — master ( 0086da...95aa9c )
by Oskar
22:17 queued 15:41
created

HalsteadVisitor   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 123
Duplicated Lines 5.69 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 7
loc 123
rs 10
wmc 28
lcom 1
cbo 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F leaveNode() 7 102 27

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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