Skip to content

Commit be22d68

Browse files
staabmondrejmirtes
authored andcommitted
Consider LastConditionVisitor in ConstantLooseComparisonRule
1 parent c426883 commit be22d68

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

src/Rules/Comparison/ConstantLooseComparisonRule.php

+5
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PhpParser\Node;
66
use PHPStan\Analyser\Scope;
7+
use PHPStan\Parser\LastConditionVisitor;
78
use PHPStan\Rules\Rule;
89
use PHPStan\Rules\RuleErrorBuilder;
910
use PHPStan\Type\Constant\ConstantBooleanType;
@@ -46,6 +47,10 @@ public function processNode(Node $node, Scope $scope): array
4647
))->build(),
4748
];
4849
} elseif ($this->checkAlwaysTrueLooseComparison) {
50+
if ($node->getAttribute(LastConditionVisitor::ATTRIBUTE_NAME) === true) {
51+
return [];
52+
}
53+
4954
return [
5055
RuleErrorBuilder::message(sprintf(
5156
'Loose comparison using %s between %s and %s will always evaluate to true.',

tests/PHPStan/Rules/Comparison/ConstantLooseComparisonRuleTest.php

+20
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ public function testRule(): void
2626
"Loose comparison using == between 0 and '1' will always evaluate to false.",
2727
20,
2828
],
29+
[
30+
"Loose comparison using == between 0 and '1' will always evaluate to false.",
31+
27,
32+
],
33+
[
34+
"Loose comparison using == between 0 and '1' will always evaluate to false.",
35+
33,
36+
],
2937
]);
3038
}
3139

@@ -41,6 +49,18 @@ public function testRuleAlwaysTrue(): void
4149
"Loose comparison using == between 0 and '1' will always evaluate to false.",
4250
20,
4351
],
52+
[
53+
"Loose comparison using == between 0 and '1' will always evaluate to false.",
54+
27,
55+
],
56+
[
57+
"Loose comparison using == between 0 and '1' will always evaluate to false.",
58+
33,
59+
],
60+
[
61+
"Loose comparison using == between 0 and '0' will always evaluate to true.",
62+
35,
63+
],
4464
]);
4565
}
4666

tests/PHPStan/Rules/Comparison/data/loose-comparison.php

+18
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,22 @@ public function doFoo(string $s, string $i): void
2222
}
2323
}
2424

25+
public function doFooBar(): void
26+
{
27+
if (0 == "1") {
28+
29+
} elseif (0 == "0") { // always-true should not be reported because last condition
30+
31+
}
32+
33+
if (0 == "1") {
34+
35+
} elseif (0 == "0") { // always-true should be reported, because another condition below
36+
37+
} elseif (rand (0, 1)) {
38+
39+
}
40+
41+
}
42+
2543
}

0 commit comments

Comments
 (0)