Skip to content

Commit 793a6d4

Browse files
authored
Allow list to declare vars in foreach (#35)
* Tests: Add foreach with `list` expansion to fixture * Use T_FOREACH in checkForForeachLoopVar The open bracket check could be fooled by a `list()`.
1 parent 7b26ad1 commit 793a6d4

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -537,12 +537,16 @@ protected function checkForForeachLoopVar(File $phpcsFile, $stackPtr, $varName,
537537
$token = $tokens[$stackPtr];
538538

539539
// Are we a foreach loopvar?
540-
$openPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
540+
$lastStatementPtr = $phpcsFile->findPrevious(T_SEMICOLON, $stackPtr);
541+
if ($lastStatementPtr === false) {
542+
$lastStatementPtr = 0;
543+
}
544+
$openPtr = $phpcsFile->findPrevious(T_FOREACH, $stackPtr, $lastStatementPtr);
541545
if ($openPtr === false) {
542546
return false;
543547
}
544548

545-
// Is there an 'as' token between us and the opening bracket?
549+
// Is there an 'as' token between us and the foreach?
546550
if ($phpcsFile->findPrevious(T_AS, $stackPtr - 1, $openPtr) === false) {
547551
return false;
548552
}

VariableAnalysis/Tests/CodeAnalysis/fixtures/FunctionWithForeachFixture.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,15 @@ function function_with_defined_foreach() {
5454
foreach ($array as $key4 => &$value4) {
5555
}
5656
}
57+
58+
$data = [
59+
['foo', 'Foo'],
60+
['bar', 'Bar'],
61+
62+
];
63+
foreach ($data as $val) {
64+
echo json_encode($val);
65+
}
66+
foreach ($data as list($name, $label)) {
67+
printf('<div id="%s">%s</div>', $name, $label);
68+
}

0 commit comments

Comments
 (0)