Skip to content

Commit 287ac33

Browse files
committed
EarlyExitSniff: Fixed false positive
1 parent 06a7e06 commit 287ac33

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

SlevomatCodingStandard/Sniffs/ControlStructures/EarlyExitSniff.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,16 +206,32 @@ private function processElseIf(File $phpcsFile, int $elseIfPointer): void
206206

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

209+
$elseIfEarlyExitPointer = null;
210+
$previousConditionEarlyExitPointer = null;
211+
209212
foreach ($allConditionsPointers as $conditionPointer) {
210-
if ($elseIfPointer === $conditionPointer) {
213+
$conditionEarlyExitPointer = $this->findEarlyExitInScope($phpcsFile, $tokens[$conditionPointer]['scope_opener'], $tokens[$conditionPointer]['scope_closer']);
214+
215+
if ($conditionPointer === $elseIfPointer) {
216+
$elseIfEarlyExitPointer = $conditionEarlyExitPointer;
211217
break;
212218
}
213219

214-
if (!$this->isEarlyExitInScope($phpcsFile, $tokens[$conditionPointer]['scope_opener'], $tokens[$conditionPointer]['scope_closer'])) {
220+
$previousConditionEarlyExitPointer = $conditionEarlyExitPointer;
221+
222+
if ($conditionEarlyExitPointer === null) {
215223
return;
216224
}
217225
}
218226

227+
if (
228+
$previousConditionEarlyExitPointer !== null
229+
&& $tokens[$previousConditionEarlyExitPointer]['code'] === T_YIELD
230+
&& $tokens[$elseIfEarlyExitPointer]['code'] === T_YIELD
231+
) {
232+
return;
233+
}
234+
219235
$fix = $phpcsFile->addFixableError(
220236
'Use if instead of elseif.',
221237
$elseIfPointer,

tests/Sniffs/ControlStructures/data/earlyExitNoErrors.php

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,20 @@ function allConditionsWithEarlyExitButCodeAfter($dateTime) {
193193

194194
function twoYields(bool $flag)
195195
{
196-
if ($flag) {
197-
yield 1;
198-
} else {
199-
yield 2;
200-
}
196+
if ($flag) {
197+
yield 1;
198+
} else {
199+
yield 2;
200+
}
201+
}
202+
203+
function manyYields(bool $flag)
204+
{
205+
if ($flag) {
206+
yield 1;
207+
} elseif (!$flag) {
208+
yield 2;
209+
} else {
210+
yield 3;
211+
}
201212
}

0 commit comments

Comments
 (0)