Completed
Pull Request — master (#230)
by
unknown
04:39
created

YodaCondition   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 49
ccs 26
cts 26
cp 1
rs 10
wmc 10
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
D pass() 0 26 9
A getRegister() 0 11 1
1
<?php
2
/**
3
 * @author Alexey Kolpakov https://github.com/alhimik45 <[email protected]>
4
 */
5
6
namespace PHPSA\Analyzer\Pass\Statement;
7
8
use PhpParser\Node\Expr;
9
use PhpParser\Node\Expr\BinaryOp\Equal;
10
use PhpParser\Node\Expr\BinaryOp\Identical;
11
use PhpParser\Node\Expr\BinaryOp\NotEqual;
12
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
13
use PhpParser\Node\Expr\Variable;
14
use PhpParser\Node\Scalar;
15
use PhpParser\Node\Stmt;
16
use PhpParser\Node\Stmt\Case_;
17
use PhpParser\Node\Stmt\Do_;
18
use PhpParser\Node\Stmt\ElseIf_;
19
use PhpParser\Node\Stmt\For_;
20
use PhpParser\Node\Stmt\If_;
21
use PhpParser\Node\Stmt\While_;
22
use PHPSA\Analyzer\Pass;
23
use PHPSA\Context;
24
25
class YodaCondition implements Pass\AnalyzerPassInterface
26
{
27
    /**
28
     * @param $stmt
29
     * @param Context $context
30
     * @return bool
31
     */
32 17
    public function pass($stmt, Context $context)
33
    {
34 17
        $condition = $stmt->cond;
35
36 17
        if ($stmt instanceof For_ && count($stmt->cond) > 0) { // For is the only one that has an array as condition
37 3
            $condition = $condition[0];
38 3
        }
39
40 17
        if ($condition instanceof Equal ||
41 12
            $condition instanceof NotEqual ||
42 12
            $condition instanceof Identical ||
43
            $condition instanceof NotIdentical
44 17
        ) {
45 8
            if ($condition->left instanceof Scalar &&
46 8
                $condition->right instanceof Variable) {
47 1
                $context->notice(
48 1
                    'yoda_condition',
49 1
                    'Avoid Yoda conditions, where constants are placed first in comparisons',
50
                    $stmt
51 1
                );
52 1
                return true;
53
            }
54 8
        }
55
56 17
        return false;
57
    }
58
59
    /**
60
     * @return array
61
     */
62 1
    public function getRegister()
63
    {
64
        return [
65 1
            If_::class,
66 1
            ElseIf_::class,
67 1
            For_::class,
68 1
            While_::class,
69 1
            Do_::class,
70 1
            Case_::class,
71 1
        ];
72
    }
73
}
74