-
Notifications
You must be signed in to change notification settings - Fork 426
/
FunctionReturnTypeCheck.php
110 lines (94 loc) · 2.61 KB
/
FunctionReturnTypeCheck.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php declare(strict_types = 1);
namespace PHPStan\Rules;
use Generator;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PHPStan\Analyser\Scope;
use PHPStan\Parser\OversizedArrayVisitor;
use PHPStan\Type\GenericTypeVariableResolver;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\VerbosityLevel;
use PHPStan\Type\VoidType;
use function sprintf;
class FunctionReturnTypeCheck
{
public function __construct(private RuleLevelHelper $ruleLevelHelper)
{
}
/**
* @return RuleError[]
*/
public function checkReturnType(
Scope $scope,
Type $returnType,
?Expr $returnValue,
Node $returnNode,
string $emptyReturnStatementMessage,
string $voidMessage,
string $typeMismatchMessage,
string $neverMessage,
bool $isGenerator,
): array
{
$returnType = TypeUtils::resolveLateResolvableTypes($returnType);
if ($returnType instanceof NeverType && $returnType->isExplicit()) {
return [
RuleErrorBuilder::message($neverMessage)
->line($returnNode->getLine())
->build(),
];
}
if ($isGenerator) {
if (!$returnType instanceof TypeWithClassName) {
return [];
}
$returnType = GenericTypeVariableResolver::getType(
$returnType,
Generator::class,
'TReturn',
);
if ($returnType === null) {
return [];
}
}
$isVoidSuperType = (new VoidType())->isSuperTypeOf($returnType);
$verbosityLevel = VerbosityLevel::getRecommendedLevelByType($returnType, null);
if ($returnValue === null) {
if (!$isVoidSuperType->no()) {
return [];
}
return [
RuleErrorBuilder::message(sprintf(
$emptyReturnStatementMessage,
$returnType->describe($verbosityLevel),
))->line($returnNode->getLine())->build(),
];
}
if ($returnNode instanceof Expr\Yield_ || $returnNode instanceof Expr\YieldFrom) {
return [];
}
$returnValueType = $scope->getType($returnValue);
$verbosityLevel = VerbosityLevel::getRecommendedLevelByType($returnType, $returnValueType);
if ($isVoidSuperType->yes()) {
return [
RuleErrorBuilder::message(sprintf(
$voidMessage,
$returnValueType->describe($verbosityLevel),
))->line($returnNode->getLine())->build(),
];
}
if (!$returnValue->hasAttribute(OversizedArrayVisitor::OVERSIZED) && !$this->ruleLevelHelper->accepts($returnType, $returnValueType, $scope->isDeclareStrictTypes())) {
return [
RuleErrorBuilder::message(sprintf(
$typeMismatchMessage,
$returnType->describe($verbosityLevel),
$returnValueType->describe($verbosityLevel),
))->line($returnNode->getLine())->build(),
];
}
return [];
}
}