From 14cb6d0da4390f484e09e2d73a4ac3645d919b84 Mon Sep 17 00:00:00 2001 From: ondrejmirtes <104888+ondrejmirtes@users.noreply.github.com> Date: Tue, 14 Apr 2026 07:33:34 +0000 Subject: [PATCH] Add regression test for `@var` annotation before `foreach` not defining the expression variable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add regression test for phpstan/phpstan#6688 verifying that `@var` PHPDoc annotations before `foreach` correctly define the expression variable in scope - Test covers the original issue: `/** @var string[][] $result */ foreach ($result as $data)` and the maintainer's reproduction: `/** @var string[] $c */ foreach ($c as $v)` - The fix was applied in commit 4a0884538 by moving the `processVarAnnotation` call before `processExprNode` in the `Foreach_` branch of `NodeScopeResolver` - Investigated analogous constructs (if, while, do-while, for, switch, match): all are correctly handled by the general `processStmtVarAnnotation` call at the top of `processStmtNode` — only `Foreach_` was excluded from that general handling and needed its own pre-expression annotation processing --- .../Rules/Variables/DefinedVariableRuleTest.php | 14 ++++++++++++++ tests/PHPStan/Rules/Variables/data/bug-6688.php | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/PHPStan/Rules/Variables/data/bug-6688.php diff --git a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php index 207070c7627..6da8dfb7a50 100644 --- a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php +++ b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php @@ -1517,4 +1517,18 @@ public function testBug11218(): void $this->analyse([__DIR__ . '/data/bug-11218.php'], []); } + public function testBug6688(): void + { + $this->cliArgumentsVariablesRegistered = true; + $this->polluteScopeWithLoopInitialAssignments = false; + $this->checkMaybeUndefinedVariables = true; + $this->polluteScopeWithAlwaysIterableForeach = true; + $this->analyse([__DIR__ . '/data/bug-6688.php'], [ + [ + 'Variable $a might not be defined.', + 5, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Variables/data/bug-6688.php b/tests/PHPStan/Rules/Variables/data/bug-6688.php new file mode 100644 index 00000000000..c1c98925c2a --- /dev/null +++ b/tests/PHPStan/Rules/Variables/data/bug-6688.php @@ -0,0 +1,17 @@ +