Completed
Push — master ( 1c1274...4171d4 )
by David
23s queued 21s
created

SwitchMustContainDefaultRule   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getNodeType() 0 4 1
A processNode() 0 17 4
1
<?php
2
3
4
namespace TheCodingMachine\PHPStan\Rules\Conditionals;
5
6
use PhpParser\Node;
7
use PhpParser\Node\Stmt\Switch_;
8
use PhpParser\NodeTraverser;
9
use PhpParser\NodeVisitorAbstract;
10
use PHPStan\Analyser\Scope;
11
use PHPStan\Rules\Rule;
12
use TheCodingMachine\PHPStan\Utils\PrefixGenerator;
13
14
/**
15
 * A switch statement must always contain a "default" statement.
16
 */
17
class SwitchMustContainDefaultRule implements Rule
18
{
19
    public function getNodeType(): string
20
    {
21
        return Switch_::class;
22
    }
23
24
    /**
25
     * @param Switch_ $switch
26
     * @param \PHPStan\Analyser\Scope $scope
27
     * @return string[]
28
     */
29
    public function processNode(Node $switch, Scope $scope): array
30
    {
31
        $errors = [];
32
        $defaultFound = false;
33
        foreach ($switch->cases as $case) {
34
            if ($case->cond === null) {
35
                $defaultFound = true;
36
                break;
37
            }
38
        }
39
40
        if (!$defaultFound) {
41
            $errors[] = sprintf(PrefixGenerator::generatePrefix($scope).'switch statement does not have a "default" case. If your code is supposed to enter at least one "case" or another, consider adding a "default" case that throws an exception.');
42
        }
43
44
        return $errors;
45
    }
46
}
47