From 3f5277975a4c625b0fd6a29ea256a672d0bb77fa Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Tue, 4 Jul 2023 21:32:42 +0200 Subject: [PATCH] Fix processCalledMethod when anonymous classes are involved --- src/Analyser/NodeScopeResolver.php | 10 ++++++- .../data/uninitialized-property.php | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/Analyser/NodeScopeResolver.php b/src/Analyser/NodeScopeResolver.php index 1b447b8abc..c6980cfacb 100644 --- a/src/Analyser/NodeScopeResolver.php +++ b/src/Analyser/NodeScopeResolver.php @@ -4422,11 +4422,19 @@ private function processCalledMethod(MethodReflection $methodReflection): ?Metho $parserNodes = $this->parser->parseFile($fileName); $returnStatement = null; - $this->processNodesForCalledMethod($parserNodes, $fileName, $methodReflection, static function (Node $node) use (&$returnStatement): void { + $this->processNodesForCalledMethod($parserNodes, $fileName, $methodReflection, static function (Node $node, Scope $scope) use ($methodReflection, &$returnStatement): void { if (!$node instanceof MethodReturnStatementsNode) { return; } + if (!$scope->isInClass()) { + return; + } + + if ($scope->getClassReflection()->getName() !== $methodReflection->getDeclaringClass()->getName()) { + return; + } + if ($returnStatement !== null) { return; } diff --git a/tests/PHPStan/Rules/Properties/data/uninitialized-property.php b/tests/PHPStan/Rules/Properties/data/uninitialized-property.php index 37713db980..e3fa2865e1 100644 --- a/tests/PHPStan/Rules/Properties/data/uninitialized-property.php +++ b/tests/PHPStan/Rules/Properties/data/uninitialized-property.php @@ -304,3 +304,31 @@ public function doSomething() } } + +class ConfuseNodeScopeResolverWithAnonymousClass +{ + + private int $foo; + + public function __construct() + { + $this->setFoo(); + $this->doSomething(); + } + + private function setFoo() + { + $c = new class () { + public function setFoo() + { + } + }; + $this->foo = 1; + } + + public function doSomething() + { + echo $this->foo; + } + +}