Skip to content

Commit 543d8ad

Browse files
committed
Do not report do-while-false loops that are interrupted by a break statement
1 parent cec72fb commit 543d8ad

File tree

3 files changed

+45
-5
lines changed

3 files changed

+45
-5
lines changed

src/Rules/Comparison/DoWhileLoopConstantConditionRule.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,13 @@ public function processNode(Node $node, Scope $scope): array
6565
return [];
6666
}
6767
}
68+
} else {
69+
foreach ($node->getExitPoints() as $exitPoint) {
70+
$statement = $exitPoint->getStatement();
71+
if ($statement instanceof Break_) {
72+
return [];
73+
}
74+
}
6875
}
6976

7077
$addTip = function (RuleErrorBuilder $ruleErrorBuilder) use ($scope, $node): RuleErrorBuilder {

tests/PHPStan/Rules/Comparison/DoWhileLoopConstantConditionRuleTest.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,6 @@ public function testRule(): void
4343
'Do-while loop condition is always false.',
4444
46,
4545
],
46-
[
47-
'Do-while loop condition is always false.',
48-
55,
49-
],
5046
[
5147
'Do-while loop condition is always true.',
5248
64,
@@ -55,6 +51,14 @@ public function testRule(): void
5551
'Do-while loop condition is always false.',
5652
73,
5753
],
54+
[
55+
'Do-while loop condition is always false.',
56+
105,
57+
],
58+
[
59+
'Do-while loop condition is always false.',
60+
115,
61+
],
5862
]);
5963
}
6064

tests/PHPStan/Rules/Comparison/data/do-while-loop.php

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public function doBar3()
5252
if (rand(0, 1)) {
5353
break;
5454
}
55-
} while (false); // report
55+
} while (false); // do not report
5656
}
5757

5858
public function doFoo4()
@@ -95,4 +95,33 @@ public function doFoo6(array $a)
9595
}
9696
}
9797

98+
public function doFoo8(array $a)
99+
{
100+
foreach ($a as $v) {
101+
do {
102+
if (rand(0, 1)) {
103+
continue 2;
104+
}
105+
} while (false); // report
106+
}
107+
}
108+
109+
public function doFoo9(array $a)
110+
{
111+
do {
112+
foreach ($a as $v) {
113+
break;
114+
}
115+
} while (false); // report
116+
}
117+
118+
public function doFoo10(array $a)
119+
{
120+
do {
121+
foreach ($a as $v) {
122+
break 2;
123+
}
124+
} while (false); // do not report
125+
}
126+
98127
}

0 commit comments

Comments
 (0)