Skip to content

Incorrect type after strict comparison between null-safe accessed property and false #9394

Closed

Description

@devfrey

Bug report

PHPStan incorrectly strips null from object|null type after a strict comparison between null-safe accessed property and false, with an early exit.

In case a variable contains null and the null safe operator is used to access a property and strictly compare it to false, you effectively get null === false which is always false, so it is impossible to reach the early return. Therefore, the variable should remain nullable.

Strictly comparing to true and loosely comparing to false work as expected. This issue seems to be specific to === false.

Code snippet that reproduces the problem

class Order
{
    public bool $is_pre_order;
}

/** @var Order|null $order */

if ($order?->is_pre_order === false) {
    return;
}

\PHPStan\dumpType($order); // Dumped type: Order

https://phpstan.org/r/2a18319c-b78b-4951-a318-11319d823a83

Expected output

Dumped type: Order|null

Did PHPStan help you today? Did it make you happy in any way?

Thank you for your efforts 🙏

Activity

  1. added this to the Easy fixes milestone on Jun 6, 2023
  2. phpstan-bot commented on Oct 30, 2023

    @phpstan-bot
    Collaborator

    @devfrey After the latest push in 1.11.x, PHPStan now reports different result with your code snippet:

    @@ @@
    -14: Dumped type: Order
    +14: Dumped type: Order|null
    Full report
    Line Error
    14 `Dumped type: Order
  3. added a commit that references this issue on Nov 2, 2023
  4. github-actions commented on Dec 4, 2023

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

  5. locked as resolved and limited conversation to collaborators on Dec 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions