Completed
Push — master ( b7d262...3c2b8e )
by Дмитрий
05:26
created

MissingBreakStatement::checkCaseStatement()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 36
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8.125

Importance

Changes 0
Metric Value
cc 8
eloc 16
nc 5
nop 2
dl 0
loc 36
ccs 14
cts 16
cp 0.875
crap 8.125
rs 5.3846
c 0
b 0
f 0
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\Stmt;
9
use PHPSA\Analyzer\Helper\DefaultMetadataPassTrait;
10
use PHPSA\Analyzer\Pass;
11
use PHPSA\Context;
12
13
class MissingBreakStatement implements Pass\AnalyzerPassInterface
14
{
15
    use DefaultMetadataPassTrait;
16
17
    const DESCRIPTION = 'Checks for a missing break or return statement in switch cases. Can ignore empty cases and the last case.';
18
19
    /**
20
     * @param Stmt\Switch_ $switchStmt
21
     * @param Context $context
22
     * @return bool
23
     */
24 2
    public function pass(Stmt\Switch_ $switchStmt, Context $context)
25
    {
26 2
        $result = false;
27 2
        $caseStmts = $switchStmt->cases;
28
29 2
        if (count($caseStmts) < 2) {
30 1
            return $result;
31
        }
32
33 2
        array_pop($caseStmts); // the last case statement CAN have no "break" or "return"
34
35
        /** @var Stmt\Case_ $case */
36 2
        foreach ($caseStmts as $case) {
37 2
            $result = $this->checkCaseStatement($case, $context) || $result;
38
        }
39
40 2
        return $result;
41
    }
42
43
    /**
44
     * @return array
45
     */
46 2
    public function getRegister()
47
    {
48
        return [
49 2
            Stmt\Switch_::class
50
        ];
51
    }
52
53
    /**
54
     * @param Stmt\Case_ $case
55
     * @param Context $context
56
     * @return bool
57
     */
58 2
    private function checkCaseStatement(Stmt\Case_ $case, Context $context)
59
    {
60
        /*
61
         * switch(…) {
62
         *     case 41:
63
         *     case 42:
64
         *     case 43:
65
         *         return 'the truth, or almost.';
66
         * }
67
         */
68 2
        if ($case->stmts === null) {
69
            return false;
70
        }
71
72 2
        $stmt = end($case->stmts);
73 2
        while ($stmt !== false) {
74 2
            if ($stmt instanceof Stmt\Break_ || $stmt instanceof Stmt\Return_
75 2
            || $stmt instanceof Stmt\Throw_ || $stmt instanceof Stmt\Continue_) {
76 2
                break;
77
            }
78
79 1
            if (!$stmt instanceof Stmt\Nop) {
80 1
                $context->notice(
81 1
                    'missing_break_statement',
82 1
                    'Missing "break" statement',
83 1
                    $case
84
                );
85
86 1
                return true;
87
            }
88
89
            $stmt = prev($case->stmts);
90
        }
91
92 2
        return false;
93
    }
94
}
95