Completed
Push — master ( bdaaad...4f4372 )
by personal
06:57 queued 04:36
created

MaintainabilityIndexVisitor::leaveNode()   C

Complexity

Conditions 10
Paths 19

Size

Total Lines 55
Code Lines 35

Duplication

Lines 6
Ratio 10.91 %

Importance

Changes 0
Metric Value
cc 10
eloc 35
nc 19
nop 1
dl 6
loc 55
rs 6.8372
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
namespace Hal\Metric\Class_\Component;
3
4
use Hal\Metric\FunctionMetric;
5
use Hal\Metric\Metrics;
6
use Hoa\Ruler\Model\Bag\Scalar;
7
use PhpParser\Node;
8
use PhpParser\Node\Stmt;
9
use PhpParser\NodeVisitorAbstract;
10
11
/**
12
 * Calculates Maintainability Index
13
 *
14
 *      According to Wikipedia, "Maintainability Index is a software metric which measures how maintainable (easy to
15
 *      support and change) the source code is. The maintainability index is calculated as a factored formula consisting
16
 *      of Lines Of Code, Cyclomatic Complexity and Halstead volume."
17
 *
18
 *      MIwoc: Maintainability Index without comments
19
 *      MIcw: Maintainability Index comment weight
20
 *      MI: Maintainability Index = MIwoc + MIcw
21
 *
22
 *      MIwoc = 171 - 5.2 * ln(aveV) -0.23 * aveG -16.2 * ln(aveLOC)
23
 *      MIcw = 50 * sin(sqrt(2.4 * perCM))
24
 *      MI = MIwoc + MIcw
25
 *
26
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
27
 */
28
class MaintainabilityIndexVisitor extends NodeVisitorAbstract
29
{
30
31
    /**
32
     * @var Metrics
33
     */
34
    private $metrics;
35
36
    /**
37
     * ClassEnumVisitor constructor.
38
     * @param Metrics $metrics
39
     */
40
    public function __construct(Metrics $metrics)
41
    {
42
        $this->metrics = $metrics;
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    public function leaveNode(Node $node)
49
    {
50
        if ($node instanceof Stmt\Class_) {
51
52 View Code Duplication
            if ($node instanceof Stmt\Class_) {
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...
53
                $classOrFunction = $this->metrics->get($node->namespacedName->toString());
0 ignored issues
show
Bug introduced by
The property namespacedName does not seem to exist in PhpParser\Node\Stmt\Class_.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
Are you sure the assignment to $classOrFunction is correct as $this->metrics->get($nod...spacedName->toString()) (which targets Hal\Metric\Metrics::get()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
54
            } else {
55
                $classOrFunction = new FunctionMetric($node->name);
56
                $this->metrics->attach($classOrFunction);
57
            }
58
            if (null === $lloc = $classOrFunction->get('lloc')) {
59
                throw new \LogicException('please enable length (lloc) visitor first');
60
            }
61
            if (null === $cloc = $classOrFunction->get('cloc')) {
62
                throw new \LogicException('please enable length (cloc) visitor first');
63
            }
64
            if (null === $loc = $classOrFunction->get('loc')) {
65
                throw new \LogicException('please enable length (loc) visitor first');
66
            }
67
            if (null === $ccn = $classOrFunction->get('ccn')) {
68
                throw new \LogicException('please enable McCabe visitor first');
69
            }
70
            if (null === $volume = $classOrFunction->get('volume')) {
71
                throw new \LogicException('please enable Halstead visitor first');
72
            }
73
74
            // maintainability index without comment
75
            $MIwoC = max(
76
                (171
77
                    - (5.2 * \log($volume))
78
                    - (0.23 * $ccn)
79
                    - (16.2 * \log($lloc))
80
                ) * 100 / 171
81
                , 0);
82
            if (is_infinite($MIwoC)) {
83
                $MIwoC = 171;
84
            }
85
86
            // comment weight
87
            if ($loc > 0) {
88
                $CM = $cloc / $loc;
89
                $commentWeight = 50 * sin(sqrt(2.4 * $CM));
90
            }
91
92
            // maintainability index
93
            $mi = $MIwoC + $commentWeight;
0 ignored issues
show
Bug introduced by
The variable $commentWeight does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
94
95
            // save result
96
            $classOrFunction
97
                ->set('mi', round($mi, 2))
98
                ->set('mIwoC', round($MIwoC, 2))
99
                ->set('commentWeight', round($commentWeight, 2));
100
            $this->metrics->attach($classOrFunction);
101
        }
102
    }
103
}
104