diff --git a/SlevomatCodingStandard/Sniffs/ControlStructures/EarlyExitSniff.php b/SlevomatCodingStandard/Sniffs/ControlStructures/EarlyExitSniff.php index bfd86b329..fd88ccdfe 100644 --- a/SlevomatCodingStandard/Sniffs/ControlStructures/EarlyExitSniff.php +++ b/SlevomatCodingStandard/Sniffs/ControlStructures/EarlyExitSniff.php @@ -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, diff --git a/tests/Sniffs/ControlStructures/data/earlyExitNoErrors.php b/tests/Sniffs/ControlStructures/data/earlyExitNoErrors.php index 1b99d42af..8ff99276f 100644 --- a/tests/Sniffs/ControlStructures/data/earlyExitNoErrors.php +++ b/tests/Sniffs/ControlStructures/data/earlyExitNoErrors.php @@ -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; + } }