Skip to content

Commit 0681b8a

Browse files
committed
Don't report "is always true/false" for conditionally defined variables
1 parent 88d5b8c commit 0681b8a

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

src/Rules/Comparison/ConstantConditionRuleHelper.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PhpParser\Node\Expr\MethodCall;
88
use PHPStan\Analyser\Scope;
99
use PHPStan\Type\BooleanType;
10+
use function is_string;
1011

1112
final class ConstantConditionRuleHelper
1213
{
@@ -18,7 +19,7 @@ public function __construct(
1819
{
1920
}
2021

21-
public function shouldSkip(Scope $scope, Expr $expr): bool
22+
private function shouldSkip(Scope $scope, Expr $expr): bool
2223
{
2324
if (
2425
$expr instanceof Expr\BinaryOp\Equal
@@ -57,6 +58,14 @@ public function shouldSkip(Scope $scope, Expr $expr): bool
5758
}
5859
}
5960

61+
if (
62+
$expr instanceof Expr\Variable
63+
&& is_string($expr->name)
64+
&& !$scope->hasVariableType($expr->name)->yes()
65+
) {
66+
return true;
67+
}
68+
6069
return false;
6170
}
6271

tests/PHPStan/Rules/Comparison/IfConstantConditionRuleTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,4 +173,10 @@ public function testBug4912(): void
173173
$this->analyse([__DIR__ . '/data/bug-4912.php'], []);
174174
}
175175

176+
public function testBug6830(): void
177+
{
178+
$this->treatPhpDocTypesAsCertain = true;
179+
$this->analyse([__DIR__ . '/data/bug-6830.php'], []);
180+
}
181+
176182
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
namespace Bug6830;
4+
5+
function test(bool $do): void
6+
{
7+
8+
if ($do) {
9+
10+
$x = 9999;
11+
}
12+
13+
foreach ([1, 2, 3] as $whatever) {
14+
15+
if ($do) {
16+
17+
if ($x) {
18+
19+
$x = 123;
20+
}
21+
}
22+
}
23+
}
24+
25+
26+

0 commit comments

Comments
 (0)