diff --git a/src/Analyser/MutatingScope.php b/src/Analyser/MutatingScope.php index 213ed039a1..23db83baa1 100644 --- a/src/Analyser/MutatingScope.php +++ b/src/Analyser/MutatingScope.php @@ -3298,6 +3298,7 @@ public function filterBySpecifiedTypes(SpecifiedTypes $specifiedTypes): self } $conditions = []; + $originallySpecifiedExprStrings = $specifiedExpressions; $prevSpecifiedCount = -1; while (count($specifiedExpressions) !== $prevSpecifiedCount) { $prevSpecifiedCount = count($specifiedExpressions); @@ -3308,6 +3309,12 @@ public function filterBySpecifiedTypes(SpecifiedTypes $specifiedTypes): self // Pass 1: Prefer exact matches foreach ($conditionalExpressions as $conditionalExpression) { + if ( + $conditionalExpression->getTypeHolder()->getCertainty()->no() + && array_key_exists($conditionalExprString, $originallySpecifiedExprStrings) + ) { + continue; + } foreach ($conditionalExpression->getConditionExpressionTypeHolders() as $holderExprString => $conditionalTypeHolder) { if ( !array_key_exists($holderExprString, $specifiedExpressions) diff --git a/tests/PHPStan/Analyser/nsrt/bug-14645.php b/tests/PHPStan/Analyser/nsrt/bug-14645.php new file mode 100644 index 0000000000..459fcedb79 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-14645.php @@ -0,0 +1,111 @@ +a !== null && $this->b !== null) { + throw new \LogicException(); + } + + if ($this->a !== null) { + $this->a->check(); + } + + if ($this->b !== null) { + assertType('Bug14645\C', $this->b); + $this->b->check(); + } + + return true; + } +} + +final class VariableAnalog +{ + public function test(?\stdClass $a, ?\stdClass $b): void + { + if ($a !== null && $b !== null) { + throw new \LogicException(); + } + + if ($a !== null) { + echo $a->foo; + } + + if ($b !== null) { + assertType('stdClass', $b); + echo $b->bar; + } + } +} + +final class ReversedOrder +{ + public function __construct(private ?self $a, private ?self $b) + { + } + + public function check(): bool + { + if ($this->a !== null && $this->b !== null) { + throw new \LogicException(); + } + + if ($this->b !== null) { + $this->b->check(); + } + + if ($this->a !== null) { + assertType('Bug14645\ReversedOrder', $this->a); + $this->a->check(); + } + + return true; + } +} + +final class ThreeProperties +{ + public function __construct( + private ?self $a, + private ?self $b, + private ?self $c, + ) { + } + + public function check(): bool + { + if ($this->a !== null && $this->b !== null) { + throw new \LogicException(); + } + + if ($this->a !== null && $this->c !== null) { + throw new \LogicException(); + } + + if ($this->a !== null) { + $this->a->check(); + } + + if ($this->b !== null) { + assertType('Bug14645\ThreeProperties', $this->b); + $this->b->check(); + } + + if ($this->c !== null) { + assertType('Bug14645\ThreeProperties', $this->c); + $this->c->check(); + } + + return true; + } +}