Skip to content

Commit

Permalink
Fix ClosureReturnStatementsNode
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jan 18, 2021
1 parent 2d2da19 commit a81a8c3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
9 changes: 2 additions & 7 deletions src/Analyser/NodeScopeResolver.php
Expand Up @@ -2304,14 +2304,9 @@ private function processClosureNode(

$gatheredReturnStatements = [];
$gatheredYieldStatements = [];
$encounteredAnotherClosure = false;
$closureStmtsCallback = static function (\PhpParser\Node $node, Scope $scope) use ($nodeCallback, &$gatheredReturnStatements, &$gatheredYieldStatements, &$encounteredAnotherClosure): void {
$closureStmtsCallback = static function (\PhpParser\Node $node, Scope $scope) use ($nodeCallback, &$gatheredReturnStatements, &$gatheredYieldStatements, &$closureScope): void {
$nodeCallback($node, $scope);
if ($encounteredAnotherClosure) {
return;
}
if ($node instanceof Expr\Closure || ($node instanceof New_ && $node->class instanceof Class_)) {
$encounteredAnotherClosure = true;
if ($scope->getAnonymousFunctionReflection() !== $closureScope->getAnonymousFunctionReflection()) {
return;
}
if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {
Expand Down
12 changes: 12 additions & 0 deletions tests/PHPStan/Rules/Functions/ClosureReturnTypeRuleTest.php
Expand Up @@ -43,6 +43,18 @@ public function testClosureReturnTypeRule(): void
'Anonymous function should return array()|null but empty return statement found.',
88,
],
[
'Anonymous function should return string but returns int.',
105,
],
[
'Anonymous function should return string but returns int.',
115,
],
[
'Anonymous function should return string but returns int.',
118,
],
]);
}

Expand Down
18 changes: 18 additions & 0 deletions tests/PHPStan/Rules/Functions/data/closureReturnTypes.php
Expand Up @@ -99,3 +99,21 @@ function (): int {

return 'bar';
};

function (): string {
if (rand(0, 1)) {
return 1;
}

$c = new class () {
public function doFoo(): int {
return 2;
}
};

if (rand(0, 1)) {
return 3;
}

return 4;
};

0 comments on commit a81a8c3

Please sign in to comment.