From f6b34f2ac86d2830f53ba51601067232ea1bf6d6 Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Fri, 30 Jun 2023 14:19:00 +0200 Subject: [PATCH] Fix processing switch with complex case conditions Closes https://github.com/phpstan/phpstan/issues/5326 --- src/Analyser/NodeScopeResolver.php | 2 +- .../Analyser/LegacyNodeScopeResolverTest.php | 2 +- .../Rules/Variables/DefinedVariableRuleTest.php | 9 +++++++++ tests/PHPStan/Rules/Variables/data/bug-5326.php | 13 +++++++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 tests/PHPStan/Rules/Variables/data/bug-5326.php diff --git a/src/Analyser/NodeScopeResolver.php b/src/Analyser/NodeScopeResolver.php index b85f2cbd94..02db119f5c 100644 --- a/src/Analyser/NodeScopeResolver.php +++ b/src/Analyser/NodeScopeResolver.php @@ -1188,7 +1188,7 @@ private function processStmtNode( $scopeForBranches = $caseResult->getScope(); $hasYield = $hasYield || $caseResult->hasYield(); $throwPoints = array_merge($throwPoints, $caseResult->getThrowPoints()); - $branchScope = $scopeForBranches->filterByTruthyValue($condExpr); + $branchScope = $caseResult->getTruthyScope()->filterByTruthyValue($condExpr); } else { $hasDefaultCase = true; $branchScope = $scopeForBranches; diff --git a/tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php b/tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php index d444010cd5..06cc71c72c 100644 --- a/tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php @@ -3983,7 +3983,7 @@ public function testNotSwitchInstanceof(): void { $this->assertTypes( __DIR__ . '/data/switch-instanceof-not.php', - '*ERROR*', + '*NEVER*', '$foo', ); } diff --git a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php index f78377e721..9d84ab9035 100644 --- a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php +++ b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php @@ -967,4 +967,13 @@ public function testBug9474(): void $this->analyse([__DIR__ . '/data/bug-9474.php'], []); } + public function testBug5326(): void + { + $this->cliArgumentsVariablesRegistered = true; + $this->polluteScopeWithLoopInitialAssignments = true; + $this->checkMaybeUndefinedVariables = true; + $this->polluteScopeWithAlwaysIterableForeach = true; + $this->analyse([__DIR__ . '/data/bug-5326.php'], []); + } + } diff --git a/tests/PHPStan/Rules/Variables/data/bug-5326.php b/tests/PHPStan/Rules/Variables/data/bug-5326.php new file mode 100644 index 0000000000..f1c87aecae --- /dev/null +++ b/tests/PHPStan/Rules/Variables/data/bug-5326.php @@ -0,0 +1,13 @@ +