From 7ddfa174a60a15e584c7e6f4fec82237ccd70da8 Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Sat, 11 Sep 2021 22:47:56 +0200 Subject: [PATCH] Enter assignment of property fetch's var when in null coalesce operator --- src/Analyser/NodeScopeResolver.php | 10 ++++++++-- .../Rules/Variables/DefinedVariableRuleTest.php | 10 ++++++++++ tests/PHPStan/Rules/Variables/data/bug-3283.php | 15 +++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 tests/PHPStan/Rules/Variables/data/bug-3283.php diff --git a/src/Analyser/NodeScopeResolver.php b/src/Analyser/NodeScopeResolver.php index 05765a86f8..14621c624f 100644 --- a/src/Analyser/NodeScopeResolver.php +++ b/src/Analyser/NodeScopeResolver.php @@ -2326,8 +2326,14 @@ static function () use ($expr, $rightResult): MutatingScope { } elseif ($expr instanceof Coalesce) { $nonNullabilityResult = $this->ensureNonNullability($scope, $expr->left, false); - if ($expr->left instanceof PropertyFetch || $expr->left instanceof StaticPropertyFetch || $expr->left instanceof Expr\NullsafePropertyFetch) { - $scope = $nonNullabilityResult->getScope(); + if ($expr->left instanceof PropertyFetch || $expr->left instanceof Expr\NullsafePropertyFetch) { + $scope = $this->lookForEnterVariableAssign($nonNullabilityResult->getScope(), $expr->left->var); + } elseif ($expr->left instanceof StaticPropertyFetch) { + if ($expr->left->class instanceof Expr) { + $scope = $this->lookForEnterVariableAssign($nonNullabilityResult->getScope(), $expr->left->class); + } else { + $scope = $nonNullabilityResult->getScope(); + } } else { $scope = $this->lookForEnterVariableAssign($nonNullabilityResult->getScope(), $expr->left); } diff --git a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php index f09b906189..3beb38ad2b 100644 --- a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php +++ b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php @@ -840,4 +840,14 @@ public function testBug4412(): void ]); } + public function testBug3283(): void + { + $this->cliArgumentsVariablesRegistered = true; + $this->polluteScopeWithLoopInitialAssignments = false; + $this->polluteCatchScopeWithTryAssignments = false; + $this->checkMaybeUndefinedVariables = true; + $this->polluteScopeWithAlwaysIterableForeach = true; + $this->analyse([__DIR__ . '/data/bug-3283.php'], []); + } + } diff --git a/tests/PHPStan/Rules/Variables/data/bug-3283.php b/tests/PHPStan/Rules/Variables/data/bug-3283.php new file mode 100644 index 0000000000..6fc95b5d2d --- /dev/null +++ b/tests/PHPStan/Rules/Variables/data/bug-3283.php @@ -0,0 +1,15 @@ + 5) { + $user = new \stdClass; + $user->name = 'Thibaud'; + } + + echo $user->name ?? 'Default'; +};