Skip to content

Commit 9a99aa5

Browse files
committed
Fix MethodReturnStatementsNode to not contain statements from nested closures and anonymous functions
1 parent c70325b commit 9a99aa5

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

src/Analyser/NodeScopeResolver.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -517,8 +517,14 @@ private function processStmtNode(
517517

518518
if ($stmt->stmts !== null) {
519519
$gatheredReturnStatements = [];
520-
$statementResult = $this->processStmtNodes($stmt, $stmt->stmts, $methodScope, static function (\PhpParser\Node $node, Scope $scope) use ($nodeCallback, &$gatheredReturnStatements): void {
520+
$statementResult = $this->processStmtNodes($stmt, $stmt->stmts, $methodScope, static function (\PhpParser\Node $node, Scope $scope) use ($nodeCallback, $methodScope, &$gatheredReturnStatements): void {
521521
$nodeCallback($node, $scope);
522+
if ($scope->getFunction() !== $methodScope->getFunction()) {
523+
return;
524+
}
525+
if ($scope->isInAnonymousFunction()) {
526+
return;
527+
}
522528
if (!$node instanceof Return_) {
523529
return;
524530
}

tests/PHPStan/Rules/TooWideTypehints/TooWideMethodReturnTypehintRuleTest.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ public function testPrivate(): void
2727
'Method TooWideMethodReturnType\Foo::baz() never returns null so it can be removed from the return typehint.',
2828
18,
2929
],
30+
[
31+
'Method TooWideMethodReturnType\Foo::dolor() never returns null so it can be removed from the return typehint.',
32+
34,
33+
],
3034
]);
3135
}
3236

tests/PHPStan/Rules/TooWideTypehints/data/tooWideMethodReturnType-private.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,18 @@ public function ipsum(): ?string {
3131
return null;
3232
}
3333

34+
private function dolor(): ?string {
35+
$f = function () {
36+
return null;
37+
};
38+
39+
$c = new class () {
40+
public function doFoo() {
41+
return null;
42+
}
43+
};
44+
45+
return 'str';
46+
}
47+
3448
}

0 commit comments

Comments
 (0)