From 0681b8aac5ee5eb6f187a559addb5cfd4fded313 Mon Sep 17 00:00:00 2001 From: Markus Staab Date: Sat, 2 Nov 2024 14:34:10 +0100 Subject: [PATCH] Don't report "is always true/false" for conditionally defined variables --- .../ConstantConditionRuleHelper.php | 11 +++++++- .../IfConstantConditionRuleTest.php | 6 +++++ .../Rules/Comparison/data/bug-6830.php | 26 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 tests/PHPStan/Rules/Comparison/data/bug-6830.php diff --git a/src/Rules/Comparison/ConstantConditionRuleHelper.php b/src/Rules/Comparison/ConstantConditionRuleHelper.php index 36b2c569d8..fac2895b24 100644 --- a/src/Rules/Comparison/ConstantConditionRuleHelper.php +++ b/src/Rules/Comparison/ConstantConditionRuleHelper.php @@ -7,6 +7,7 @@ use PhpParser\Node\Expr\MethodCall; use PHPStan\Analyser\Scope; use PHPStan\Type\BooleanType; +use function is_string; final class ConstantConditionRuleHelper { @@ -18,7 +19,7 @@ public function __construct( { } - public function shouldSkip(Scope $scope, Expr $expr): bool + private function shouldSkip(Scope $scope, Expr $expr): bool { if ( $expr instanceof Expr\BinaryOp\Equal @@ -57,6 +58,14 @@ public function shouldSkip(Scope $scope, Expr $expr): bool } } + if ( + $expr instanceof Expr\Variable + && is_string($expr->name) + && !$scope->hasVariableType($expr->name)->yes() + ) { + return true; + } + return false; } diff --git a/tests/PHPStan/Rules/Comparison/IfConstantConditionRuleTest.php b/tests/PHPStan/Rules/Comparison/IfConstantConditionRuleTest.php index 1f03a122bd..5a509b0d9e 100644 --- a/tests/PHPStan/Rules/Comparison/IfConstantConditionRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/IfConstantConditionRuleTest.php @@ -173,4 +173,10 @@ public function testBug4912(): void $this->analyse([__DIR__ . '/data/bug-4912.php'], []); } + public function testBug6830(): void + { + $this->treatPhpDocTypesAsCertain = true; + $this->analyse([__DIR__ . '/data/bug-6830.php'], []); + } + } diff --git a/tests/PHPStan/Rules/Comparison/data/bug-6830.php b/tests/PHPStan/Rules/Comparison/data/bug-6830.php new file mode 100644 index 0000000000..d3ad065c74 --- /dev/null +++ b/tests/PHPStan/Rules/Comparison/data/bug-6830.php @@ -0,0 +1,26 @@ +