-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathDoNotThrowExceptionBaseClassRule.php
51 lines (43 loc) · 1.37 KB
/
DoNotThrowExceptionBaseClassRule.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
namespace TheCodingMachine\PHPStan\Rules\Exceptions;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
/**
* This rule checks that the base \Exception class is never thrown. Instead, developers should subclass the \Exception
* base class and throw the sub-type.
*
* @implements Rule<Node\Expr\Throw_>
*/
class DoNotThrowExceptionBaseClassRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\Throw_::class;
}
/**
* @param \PhpParser\Node\Expr\Throw_ $node
* @param \PHPStan\Analyser\Scope $scope
* @return RuleError[]
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node->expr instanceof Node\Expr\New_) {
// Only catch "throw new ..."
return [];
}
$type = $scope->getType($node->expr);
if ($type->getObjectClassNames() === ['Exception']) {
return [
RuleErrorBuilder::message('Do not throw the \Exception base class.')
->file($scope->getFile())
->line($node->getStartLine())
->tip('Instead, extend the \Exception base class. More info: http://bit.ly/subtypeexception')
->build(),
];
}
return [];
}
}