Skip to content

Commit a849f06

Browse files
committed
Fix type-specifying of expression involved in nullsafe property fetch
1 parent 3de3c85 commit a849f06

3 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎src/Analyser/TypeSpecifier.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,10 @@ private function specifyTypesForConstantBinaryExpression(
861861
{
862862
if (!$context->null() && $constantType->getValue() === false) {
863863
$types = $this->create($exprNode, $constantType, $context, false, $scope, $rootExpr);
864+
if ($exprNode instanceof Expr\NullsafeMethodCall || $exprNode instanceof Expr\NullsafePropertyFetch) {
865+
return $types;
866+
}
867+
864868
return $types->unionWith($this->specifyTypesInCondition(
865869
$scope,
866870
$exprNode,
@@ -871,6 +875,10 @@ private function specifyTypesForConstantBinaryExpression(
871875

872876
if (!$context->null() && $constantType->getValue() === true) {
873877
$types = $this->create($exprNode, $constantType, $context, false, $scope, $rootExpr);
878+
if ($exprNode instanceof Expr\NullsafeMethodCall || $exprNode instanceof Expr\NullsafePropertyFetch) {
879+
return $types;
880+
}
881+
874882
return $types->unionWith($this->specifyTypesInCondition(
875883
$scope,
876884
$exprNode,

‎tests/PHPStan/Analyser/NodeScopeResolverTest.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1184,6 +1184,10 @@ public function dataFileAsserts(): iterable
11841184
yield from $this->gatherAssertTypes(__DIR__ . '/data/allowed-subtypes-enum.php');
11851185
}
11861186

1187+
if (PHP_VERSION_ID >= 80000) {
1188+
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-10071.php');
1189+
}
1190+
11871191
yield from $this->gatherAssertTypes(__DIR__ . '/data/allowed-subtypes-datetime.php');
11881192
yield from $this->gatherAssertTypes(__DIR__ . '/data/allowed-subtypes-throwable.php');
11891193
yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/Methods/data/bug-8174.php');
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php declare(strict_types=1); // lint >= 8.0
2+
3+
namespace Bug10071;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class Foo
8+
{
9+
public ?bool $bar = null;
10+
}
11+
12+
13+
function okIfBar(?Foo $foo = null): void
14+
{
15+
if ($foo?->bar !== false) {
16+
assertType(Foo::class . '|null', $foo);
17+
} else {
18+
assertType(Foo::class, $foo);
19+
}
20+
21+
assertType(Foo::class . '|null', $foo);
22+
}

0 commit comments

Comments
 (0)