Skip to content

Commit

Permalink
Allow list to declare vars in foreach (#35)
Browse files Browse the repository at this point in the history
* Tests: Add foreach with `list` expansion to fixture

* Use T_FOREACH in checkForForeachLoopVar

The open bracket check could be fooled by a `list()`.
  • Loading branch information
sirbrillig authored Feb 12, 2018
1 parent 7b26ad1 commit 793a6d4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -537,12 +537,16 @@ protected function checkForForeachLoopVar(File $phpcsFile, $stackPtr, $varName,
$token = $tokens[$stackPtr];

// Are we a foreach loopvar?
$openPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
$lastStatementPtr = $phpcsFile->findPrevious(T_SEMICOLON, $stackPtr);
if ($lastStatementPtr === false) {
$lastStatementPtr = 0;
}
$openPtr = $phpcsFile->findPrevious(T_FOREACH, $stackPtr, $lastStatementPtr);
if ($openPtr === false) {
return false;
}

// Is there an 'as' token between us and the opening bracket?
// Is there an 'as' token between us and the foreach?
if ($phpcsFile->findPrevious(T_AS, $stackPtr - 1, $openPtr) === false) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,15 @@ function function_with_defined_foreach() {
foreach ($array as $key4 => &$value4) {
}
}

$data = [
['foo', 'Foo'],
['bar', 'Bar'],

];
foreach ($data as $val) {
echo json_encode($val);
}
foreach ($data as list($name, $label)) {
printf('<div id="%s">%s</div>', $name, $label);
}

0 comments on commit 793a6d4

Please sign in to comment.