Completed
Pull Request — master (#194)
by Enrico
04:55
created

AssignmentInCondition::checkAssignment()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 2
rs 9.4285
1
<?php
2
/**
3
 * @author Kévin Gomez https://github.com/K-Phoen <[email protected]>
4
 */
5
6
namespace PHPSA\Analyzer\Pass\Statement;
7
8
use PhpParser\Node\Expr;
9
use PhpParser\Node\Expr\Assign;
10
use PhpParser\Node\Stmt;
11
use PhpParser\Node\Stmt\Do_;
12
use PhpParser\Node\Stmt\ElseIf_;
13
use PhpParser\Node\Stmt\If_;
14
use PhpParser\Node\Stmt\Case_;
15
use PhpParser\Node\Stmt\While_;
16
use PhpParser\Node\Stmt\For_;
17
use PHPSA\Analyzer\Pass;
18
use PHPSA\Context;
19
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
20
21
class AssignmentInCondition implements Pass\ConfigurablePassInterface, Pass\AnalyzerPassInterface
22
{
23
    /**
24
     * @param $stmt
25
     * @param Context $context
26
     * @return bool
27
     */
28 14
    public function pass($stmt, Context $context)
29
    {
30 14
        $condition = $stmt->cond;
31
32 14
        if ($stmt instanceof For_ && count($stmt->cond) > 0) { // For is the only one that has an array as condition
33 2
            $condition = $condition[0];
34 2
        }
35
36 14
        if ($condition instanceof Assign) {
37 5
            $context->notice(
38 5
                'assignment_in_condition',
39 5
                'An assignment statement has been made instead of conditional statement',
40
                $stmt
41 5
            );
42 5
            return true;
43
        }
44
45 10
        return false;
46
    }
47
48
    /**
49
     * @return TreeBuilder
50
     */
51
    public function getConfiguration()
52
    {
53
        $treeBuilder = new TreeBuilder();
54
        $treeBuilder->root('assignment_in_condition')
55
            ->canBeDisabled();
56
57
        return $treeBuilder;
58
    }
59
60
    /**
61
     * @return array
62
     */
63 1
    public function getRegister()
64
    {
65
        return [
66 1
            If_::class,
67 1
            ElseIf_::class,
68 1
            For_::class,
69 1
            While_::class,
70 1
            Do_::class,
71 1
            Case_::class,
72 1
        ];
73
    }
74
}
75