Skip to content

Commit

Permalink
Start inline block scope at end of condition rather than at keyword (#…
Browse files Browse the repository at this point in the history
…230)

* Add test for inline conditional assignment and use inside else

* Start inline block scope at end of condition rather than at keyword
  • Loading branch information
sirbrillig authored Mar 9, 2021
1 parent 0991ceb commit e76e816
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,10 @@ function loopAndPushWithUndefinedArray($parts) {
$suggestions[] = $part; // undefined array variable
return $suggestions;
}

function ifElseConditionWithInlineAssignAndUseInsideElse() {
if($q = getData())
echo $q;
else
echo $q;
}
10 changes: 6 additions & 4 deletions VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -1487,19 +1487,21 @@ protected function processVaribleInsideElse(File $phpcsFile, $stackPtr, $varName
foreach ($allAssignmentIndices as $index) {
foreach ($blockIndices as $blockIndex) {
$blockToken = $tokens[$blockIndex];
Helpers::debug('looking at assignment', $index, 'at block index', $blockIndex, 'which is token', $blockToken);
Helpers::debug('for variable inside else, looking at assignment', $index, 'at block index', $blockIndex, 'which is token', $blockToken);
if (isset($blockToken['scope_opener']) && isset($blockToken['scope_closer'])) {
$scopeOpener = $blockToken['scope_opener'];
$scopeCloser = $blockToken['scope_closer'];
} else {
// If the `if` statement has no scope, it is probably inline, which means its scope is up until the next semicolon
$scopeOpener = $blockIndex + 1;
// If the `if` statement has no scope, it is probably inline, which
// means its scope is from the end of the condition up until the next
// semicolon
$scopeOpener = isset($blockToken['parenthesis_closer']) ? $blockToken['parenthesis_closer'] : $blockIndex + 1;
$scopeCloser = $phpcsFile->findNext([T_SEMICOLON], $scopeOpener);
if (! $scopeCloser) {
throw new \Exception("Cannot find scope for if condition block at index {$stackPtr} while examining variable {$varName}");
}
}
Helpers::debug('looking at scope', $index, 'between', $scopeOpener, 'and', $scopeCloser);
Helpers::debug('for variable inside else, looking at scope', $index, 'between', $scopeOpener, 'and', $scopeCloser);
if (Helpers::isIndexInsideScope($index, $scopeOpener, $scopeCloser)) {
$assignmentsInsideAttachedBlocks[] = $index;
}
Expand Down

0 comments on commit e76e816

Please sign in to comment.