Skip to content

Commit e76e816

Browse files
authored
Start inline block scope at end of condition rather than at keyword (sirbrillig#230)
* Add test for inline conditional assignment and use inside else * Start inline block scope at end of condition rather than at keyword
1 parent 0991ceb commit e76e816

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

Tests/VariableAnalysisSniff/fixtures/FunctionWithInlineIfConditionFixture.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,10 @@ function loopAndPushWithUndefinedArray($parts) {
136136
$suggestions[] = $part; // undefined array variable
137137
return $suggestions;
138138
}
139+
140+
function ifElseConditionWithInlineAssignAndUseInsideElse() {
141+
if($q = getData())
142+
echo $q;
143+
else
144+
echo $q;
145+
}

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1487,19 +1487,21 @@ protected function processVaribleInsideElse(File $phpcsFile, $stackPtr, $varName
14871487
foreach ($allAssignmentIndices as $index) {
14881488
foreach ($blockIndices as $blockIndex) {
14891489
$blockToken = $tokens[$blockIndex];
1490-
Helpers::debug('looking at assignment', $index, 'at block index', $blockIndex, 'which is token', $blockToken);
1490+
Helpers::debug('for variable inside else, looking at assignment', $index, 'at block index', $blockIndex, 'which is token', $blockToken);
14911491
if (isset($blockToken['scope_opener']) && isset($blockToken['scope_closer'])) {
14921492
$scopeOpener = $blockToken['scope_opener'];
14931493
$scopeCloser = $blockToken['scope_closer'];
14941494
} else {
1495-
// If the `if` statement has no scope, it is probably inline, which means its scope is up until the next semicolon
1496-
$scopeOpener = $blockIndex + 1;
1495+
// If the `if` statement has no scope, it is probably inline, which
1496+
// means its scope is from the end of the condition up until the next
1497+
// semicolon
1498+
$scopeOpener = isset($blockToken['parenthesis_closer']) ? $blockToken['parenthesis_closer'] : $blockIndex + 1;
14971499
$scopeCloser = $phpcsFile->findNext([T_SEMICOLON], $scopeOpener);
14981500
if (! $scopeCloser) {
14991501
throw new \Exception("Cannot find scope for if condition block at index {$stackPtr} while examining variable {$varName}");
15001502
}
15011503
}
1502-
Helpers::debug('looking at scope', $index, 'between', $scopeOpener, 'and', $scopeCloser);
1504+
Helpers::debug('for variable inside else, looking at scope', $index, 'between', $scopeOpener, 'and', $scopeCloser);
15031505
if (Helpers::isIndexInsideScope($index, $scopeOpener, $scopeCloser)) {
15041506
$assignmentsInsideAttachedBlocks[] = $index;
15051507
}

0 commit comments

Comments
 (0)