Skip to content

Commit a81a8c3

Browse files
committed
Fix ClosureReturnStatementsNode
1 parent 2d2da19 commit a81a8c3

File tree

3 files changed

+32
-7
lines changed

3 files changed

+32
-7
lines changed

src/Analyser/NodeScopeResolver.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2304,14 +2304,9 @@ private function processClosureNode(
23042304

23052305
$gatheredReturnStatements = [];
23062306
$gatheredYieldStatements = [];
2307-
$encounteredAnotherClosure = false;
2308-
$closureStmtsCallback = static function (\PhpParser\Node $node, Scope $scope) use ($nodeCallback, &$gatheredReturnStatements, &$gatheredYieldStatements, &$encounteredAnotherClosure): void {
2307+
$closureStmtsCallback = static function (\PhpParser\Node $node, Scope $scope) use ($nodeCallback, &$gatheredReturnStatements, &$gatheredYieldStatements, &$closureScope): void {
23092308
$nodeCallback($node, $scope);
2310-
if ($encounteredAnotherClosure) {
2311-
return;
2312-
}
2313-
if ($node instanceof Expr\Closure || ($node instanceof New_ && $node->class instanceof Class_)) {
2314-
$encounteredAnotherClosure = true;
2309+
if ($scope->getAnonymousFunctionReflection() !== $closureScope->getAnonymousFunctionReflection()) {
23152310
return;
23162311
}
23172312
if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {

tests/PHPStan/Rules/Functions/ClosureReturnTypeRuleTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,18 @@ public function testClosureReturnTypeRule(): void
4343
'Anonymous function should return array()|null but empty return statement found.',
4444
88,
4545
],
46+
[
47+
'Anonymous function should return string but returns int.',
48+
105,
49+
],
50+
[
51+
'Anonymous function should return string but returns int.',
52+
115,
53+
],
54+
[
55+
'Anonymous function should return string but returns int.',
56+
118,
57+
],
4658
]);
4759
}
4860

tests/PHPStan/Rules/Functions/data/closureReturnTypes.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,21 @@ function (): int {
9999

100100
return 'bar';
101101
};
102+
103+
function (): string {
104+
if (rand(0, 1)) {
105+
return 1;
106+
}
107+
108+
$c = new class () {
109+
public function doFoo(): int {
110+
return 2;
111+
}
112+
};
113+
114+
if (rand(0, 1)) {
115+
return 3;
116+
}
117+
118+
return 4;
119+
};

0 commit comments

Comments
 (0)