Skip to content

Fix phpstan/phpstan#9455: Bug: False report Cannot call method getId() on A|null#5447

Open
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-iy55e8w
Open

Fix phpstan/phpstan#9455: Bug: False report Cannot call method getId() on A|null#5447
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-iy55e8w

Conversation

@phpstan-bot
Copy link
Copy Markdown
Collaborator

Summary

When a null check on a method call result was stored in a boolean variable (e.g., $hasA = $b->getA() !== null), and that variable was later used in an if condition, PHPStan failed to narrow the type of $b->getA() inside the branch. The inline equivalent (if ($b->getA() !== null)) worked correctly.

Changes

  • Added MethodCall and Expr\StaticCall to the allowed expression types in processSureTypesForConditionalExpressionsAfterAssign() and processSureNotTypesForConditionalExpressionsAfterAssign() in src/Analyser/ExprHandler/AssignHandler.php
  • Added regression test in tests/PHPStan/Analyser/nsrt/bug-9455.php

Root cause

When PHPStan processes an assignment like $hasA = $b->getA() !== null, it creates ConditionalExpressionHolder objects that record type narrowing to apply when the assigned variable is later used in a condition. However, the methods processSureTypesForConditionalExpressionsAfterAssign and processSureNotTypesForConditionalExpressionsAfterAssign only allowed Variable, PropertyFetch, ArrayDimFetch, and FuncCall expressions to create these holders — MethodCall and StaticCall were filtered out. This meant that type narrowing from method call null checks (like $b->getA() !== null) was never stored and thus never applied when the boolean variable was checked.

Test

The regression test verifies that $b->getA() is correctly narrowed to Bug9455\A (not Bug9455\A|null) inside an if ($hasA) block where $hasA = $b->getA() !== null.

Fixes phpstan/phpstan#9455

…d boolean variable for method calls

- Added MethodCall and StaticCall to allowed expression types in processSureTypesForConditionalExpressionsAfterAssign and processSureNotTypesForConditionalExpressionsAfterAssign
- New regression test in tests/PHPStan/Analyser/nsrt/bug-9455.php
- The root cause was that conditional expression holders were not created for method call results when assigned to a boolean variable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants