Skip to content

Commit

Permalink
Fix type-specifying of expression involved in nullsafe property fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Oct 30, 2023
1 parent 3de3c85 commit a849f06
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,10 @@ private function specifyTypesForConstantBinaryExpression(
{
if (!$context->null() && $constantType->getValue() === false) {
$types = $this->create($exprNode, $constantType, $context, false, $scope, $rootExpr);
if ($exprNode instanceof Expr\NullsafeMethodCall || $exprNode instanceof Expr\NullsafePropertyFetch) {
return $types;
}

return $types->unionWith($this->specifyTypesInCondition(
$scope,
$exprNode,
Expand All @@ -871,6 +875,10 @@ private function specifyTypesForConstantBinaryExpression(

if (!$context->null() && $constantType->getValue() === true) {
$types = $this->create($exprNode, $constantType, $context, false, $scope, $rootExpr);
if ($exprNode instanceof Expr\NullsafeMethodCall || $exprNode instanceof Expr\NullsafePropertyFetch) {
return $types;
}

return $types->unionWith($this->specifyTypesInCondition(
$scope,
$exprNode,
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1184,6 +1184,10 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/allowed-subtypes-enum.php');
}

if (PHP_VERSION_ID >= 80000) {
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-10071.php');
}

yield from $this->gatherAssertTypes(__DIR__ . '/data/allowed-subtypes-datetime.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/allowed-subtypes-throwable.php');
yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/Methods/data/bug-8174.php');
Expand Down
22 changes: 22 additions & 0 deletions tests/PHPStan/Analyser/data/bug-10071.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php declare(strict_types=1); // lint >= 8.0

namespace Bug10071;

use function PHPStan\Testing\assertType;

class Foo
{
public ?bool $bar = null;
}


function okIfBar(?Foo $foo = null): void
{
if ($foo?->bar !== false) {
assertType(Foo::class . '|null', $foo);
} else {
assertType(Foo::class, $foo);
}

assertType(Foo::class . '|null', $foo);
}

0 comments on commit a849f06

Please sign in to comment.