-
Notifications
You must be signed in to change notification settings - Fork 435
/
InvalidThrowsPhpDocValueRule.php
75 lines (61 loc) · 1.87 KB
/
InvalidThrowsPhpDocValueRule.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PhpDoc;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\FileTypeMapper;
use PHPStan\Type\ObjectType;
use PHPStan\Type\VerbosityLevel;
use PHPStan\Type\VoidType;
/**
* @implements \PHPStan\Rules\Rule<\PhpParser\Node\FunctionLike>
*/
class InvalidThrowsPhpDocValueRule implements \PHPStan\Rules\Rule
{
private FileTypeMapper $fileTypeMapper;
public function __construct(FileTypeMapper $fileTypeMapper)
{
$this->fileTypeMapper = $fileTypeMapper;
}
public function getNodeType(): string
{
return \PhpParser\Node\FunctionLike::class;
}
public function processNode(Node $node, Scope $scope): array
{
$docComment = $node->getDocComment();
if ($docComment === null) {
return [];
}
$functionName = null;
if ($node instanceof Node\Stmt\ClassMethod) {
$functionName = $node->name->name;
} elseif ($node instanceof Node\Stmt\Function_) {
$functionName = trim($scope->getNamespace() . '\\' . $node->name->name, '\\');
}
$resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
$scope->getFile(),
$scope->isInClass() ? $scope->getClassReflection()->getName() : null,
$scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
$functionName,
$docComment->getText()
);
if ($resolvedPhpDoc->getThrowsTag() === null) {
return [];
}
$phpDocThrowsType = $resolvedPhpDoc->getThrowsTag()->getType();
if ((new VoidType())->isSuperTypeOf($phpDocThrowsType)->yes()) {
return [];
}
$isThrowsSuperType = (new ObjectType(\Throwable::class))->isSuperTypeOf($phpDocThrowsType);
if ($isThrowsSuperType->yes()) {
return [];
}
return [
RuleErrorBuilder::message(sprintf(
'PHPDoc tag @throws with type %s is not subtype of Throwable',
$phpDocThrowsType->describe(VerbosityLevel::typeOnly())
))->build(),
];
}
}