Skip to content

Commit a389f2f

Browse files
bkdotcomkukulich
authored andcommitted
do...while loop should only increment once (not for both the T_DO and T_WHILE)
1 parent 24667fa commit a389f2f

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

SlevomatCodingStandard/Sniffs/Complexity/CognitiveSniff.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use PHP_CodeSniffer\Sniffs\Sniff;
77
use PHP_CodeSniffer\Util\Tokens;
88
use SlevomatCodingStandard\Helpers\FunctionHelper;
9+
use SlevomatCodingStandard\Helpers\TokenHelper;
910
use function array_filter;
1011
use function array_pop;
1112
use function array_splice;
@@ -28,6 +29,7 @@
2829
use const T_IF;
2930
use const T_INLINE_ELSE;
3031
use const T_INLINE_THEN;
32+
use const T_OPEN_CURLY_BRACKET;
3133
use const T_OPEN_PARENTHESIS;
3234
use const T_SEMICOLON;
3335
use const T_SWITCH;
@@ -248,6 +250,16 @@ public function computeForFunctionFromTokensAndPosition(int $position): int
248250
return $this->cognitiveComplexity;
249251
}
250252

253+
protected function isPartOfDo(File $phpcsFile, int $whilePointer): bool
254+
{
255+
$tokens = $phpcsFile->getTokens();
256+
257+
$parenthesisCloserPointer = $tokens[$whilePointer]['parenthesis_closer'];
258+
$pointerAfterParenthesisCloser = TokenHelper::findNextEffective($phpcsFile, $parenthesisCloserPointer + 1);
259+
260+
return $tokens[$pointerAfterParenthesisCloser]['code'] !== T_OPEN_CURLY_BRACKET;
261+
}
262+
251263
/**
252264
* Keep track of consecutive matching boolean operators, that don't receive increment.
253265
*
@@ -286,7 +298,9 @@ private function isIncrementingToken(array $token, array $tokens, int $position)
286298
$code = $token['code'];
287299

288300
if (isset(self::INCREMENTS[$code])) {
289-
return true;
301+
return $token['code'] === T_WHILE
302+
? !$this->isPartOfDo($this->phpcsFile, $position)
303+
: true;
290304
}
291305

292306
// B1. ternary operator

tests/Sniffs/Complexity/CognitiveSniffTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ public static function dataProviderFiles(): array
8686
'ternaryTest',
8787
3,
8888
],
89+
[
90+
__DIR__ . '/data/cognitive/doWhile.php',
91+
3,
92+
'doWhile',
93+
9,
94+
],
8995
];
9096
}
9197

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
function doWhile($var)
4+
{
5+
try {
6+
if (true) { // +1
7+
do { // +2 (nesting=1)
8+
for ($i = 0; $i < 10; $i++) { // +3 (nesting=2)
9+
}
10+
} while (true); // don't increment!
11+
}
12+
} catch (\Exception | \Exception $exception) { // +1
13+
if (true) { } // +2 (nesting=1)
14+
}
15+
}

0 commit comments

Comments
 (0)