Skip to content

Commit

Permalink
EarlyExitSniff: Fixed false positive
Browse files Browse the repository at this point in the history
  • Loading branch information
kukulich committed Mar 22, 2019
1 parent 06a7e06 commit 287ac33
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
20 changes: 18 additions & 2 deletions SlevomatCodingStandard/Sniffs/ControlStructures/EarlyExitSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,16 +206,32 @@ private function processElseIf(File $phpcsFile, int $elseIfPointer): void

$allConditionsPointers = $this->getAllConditionsPointers($phpcsFile, $elseIfPointer);

$elseIfEarlyExitPointer = null;
$previousConditionEarlyExitPointer = null;

foreach ($allConditionsPointers as $conditionPointer) {
if ($elseIfPointer === $conditionPointer) {
$conditionEarlyExitPointer = $this->findEarlyExitInScope($phpcsFile, $tokens[$conditionPointer]['scope_opener'], $tokens[$conditionPointer]['scope_closer']);

if ($conditionPointer === $elseIfPointer) {
$elseIfEarlyExitPointer = $conditionEarlyExitPointer;
break;
}

if (!$this->isEarlyExitInScope($phpcsFile, $tokens[$conditionPointer]['scope_opener'], $tokens[$conditionPointer]['scope_closer'])) {
$previousConditionEarlyExitPointer = $conditionEarlyExitPointer;

if ($conditionEarlyExitPointer === null) {
return;
}
}

if (
$previousConditionEarlyExitPointer !== null
&& $tokens[$previousConditionEarlyExitPointer]['code'] === T_YIELD
&& $tokens[$elseIfEarlyExitPointer]['code'] === T_YIELD
) {
return;
}

$fix = $phpcsFile->addFixableError(
'Use if instead of elseif.',
$elseIfPointer,
Expand Down
21 changes: 16 additions & 5 deletions tests/Sniffs/ControlStructures/data/earlyExitNoErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,20 @@ function allConditionsWithEarlyExitButCodeAfter($dateTime) {

function twoYields(bool $flag)
{
if ($flag) {
yield 1;
} else {
yield 2;
}
if ($flag) {
yield 1;
} else {
yield 2;
}
}

function manyYields(bool $flag)
{
if ($flag) {
yield 1;
} elseif (!$flag) {
yield 2;
} else {
yield 3;
}
}

0 comments on commit 287ac33

Please sign in to comment.