Skip to content

Start inline block scope at end of condition rather than at keyword #230

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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