Skip to content

Commit 24af403

Browse files
author
MarkBaker
committed
Resolve double-increment of the CyclomaticComplexity count for do/while loop
This is a bugfix for Issue #3468, which identified that the count was being incremented twice when calculating the score because the sniff was checking for both the T_DO and the terminating T_WHILE tokens, incrementing CYC by two (once for each token) in the do/while loop, rather than just by one (as it should). Code in the unit test .inc file has ben modified to reflect this change, and the test php file has also been modified to reflect the change in error line numbers.
1 parent 5fb9b64 commit 24af403

File tree

3 files changed

+13
-8
lines changed

3 files changed

+13
-8
lines changed

src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ public function process(File $phpcsFile, $stackPtr)
7878
T_FOR => true,
7979
T_FOREACH => true,
8080
T_WHILE => true,
81-
T_DO => true,
81+
// T_DO is not required for incrementing CYC, as the terminating while in a do/while loop triggers the branch.
82+
// T_DO => true.
8283
T_ELSEIF => true,
8384
];
8485

src/Standards/Generic/Tests/Metrics/CyclomaticComplexityUnitTest.inc

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,11 @@ function complexityTwenty()
7979

8080
switch ($condition) {
8181
case '1':
82-
if ($condition) {
83-
} else if ($cond) {
84-
}
82+
do {
83+
if ($condition) {
84+
} else if ($cond) {
85+
}
86+
} while ($cond);
8587
break;
8688
case '2':
8789
while ($cond) {
@@ -116,9 +118,11 @@ function complexityTwenty()
116118
function complexityTwentyOne()
117119
{
118120
while ($condition === true) {
119-
if ($condition) {
120-
} else if ($cond) {
121-
}
121+
do {
122+
if ($condition) {
123+
} else if ($cond) {
124+
}
125+
} while ($cond);
122126
}
123127

124128
switch ($condition) {

src/Standards/Generic/Tests/Metrics/CyclomaticComplexityUnitTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class CyclomaticComplexityUnitTest extends AbstractSniffUnitTest
2525
*/
2626
public function getErrorList()
2727
{
28-
return [116 => 1];
28+
return [118 => 1];
2929

3030
}//end getErrorList()
3131

0 commit comments

Comments
 (0)