Completed
Push — master ( 470fec...b61c37 )
by David
19s
created

MustRethrowRule   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 62
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hp$0 ➔ leaveNode() 0 6 2
A hp$0 ➔ isThrowFound() 0 4 1
A getNodeType() 0 4 1
A processNode() 0 49 2
1
<?php
2
3
4
namespace TheCodingMachine\PHPStan\Rules\Exceptions;
5
6
use Exception;
7
use function in_array;
8
use PhpParser\Node;
9
use PhpParser\Node\Stmt\Catch_;
10
use PhpParser\NodeTraverser;
11
use PhpParser\NodeVisitorAbstract;
12
use PHPStan\Analyser\Scope;
13
use PHPStan\Broker\Broker;
14
use PHPStan\Rules\Rule;
15
use RuntimeException;
16
use TheCodingMachine\PHPStan\Utils\PrefixGenerator;
17
use Throwable;
18
19
/**
20
 * When catching \Exception, \RuntimeException or \Throwable, the exception MUST be thrown again
21
 * (unless you are developing an exception handler...)
22
 */
23
class MustRethrowRule implements Rule
24
{
25
    public function getNodeType(): string
26
    {
27
        return Catch_::class;
28
    }
29
30
    /**
31
     * @param Catch_ $node
32
     * @param \PHPStan\Analyser\Scope $scope
33
     * @return string[]
34
     */
35
    public function processNode(Node $node, Scope $scope): array
36
    {
37
        // Let's only apply the filter to \Exception, \RuntimeException or \Throwable
38
        $exceptionType = null;
39
        foreach ($node->types as $type) {
40
            if (in_array((string)$type, [Exception::class, RuntimeException::class, Throwable::class], true)) {
41
                $exceptionType = (string)$type;
42
                break;
43
            }
44
        }
45
46
        if ($exceptionType === null) {
47
            return [];
48
        }
49
50
        // Let's visit and find a throw.
51
        $visitor = new class() extends NodeVisitorAbstract {
52
            private $throwFound = false;
53
54
            public function leaveNode(Node $node)
55
            {
56
                if ($node instanceof Node\Stmt\Throw_) {
0 ignored issues
show
Bug introduced by
The class PhpParser\Node\Stmt\Throw_ does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
57
                    $this->throwFound = true;
58
                }
59
            }
60
61
            /**
62
             * @return bool
63
             */
64
            public function isThrowFound(): bool
65
            {
66
                return $this->throwFound;
67
            }
68
        };
69
70
        $traverser = new NodeTraverser();
71
72
        $traverser->addVisitor($visitor);
73
74
        $traverser->traverse($node->stmts);
75
76
        $errors = [];
77
78
        if (!$visitor->isThrowFound()) {
79
            $errors[] = sprintf('%scaught "%s" must be rethrown. Either catch a more specific exception or add a "throw" clause in the "catch" block to propagate the exception.', PrefixGenerator::generatePrefix($scope), $exceptionType);
80
        }
81
82
        return $errors;
83
    }
84
}
85