Skip to content

Fix phpstan/phpstan#11610: Optional array shape property doesn't change to required after is_array#5410

Closed
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-7gcsc5e
Closed

Fix phpstan/phpstan#11610: Optional array shape property doesn't change to required after is_array#5410
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-7gcsc5e

Conversation

@phpstan-bot
Copy link
Copy Markdown
Collaborator

Summary

When an object has an optional property (e.g., object{containers?: array<int>}) and the property is checked via is_array($obj->containers ?? null), the property should be narrowed from optional to required in the truthy branch. Previously, it stayed optional.

Changes

  • Modified src/Analyser/TypeSpecifier.php in the createForExpr method: when a Coalesce expression is simplified to its left-side PropertyFetch (because the narrowed type excludes the right side), also emit a HasPropertyType constraint on the object variable — mirroring what isset() already does for property fetches.

Root cause

In createForExpr, when is_array($obj->prop ?? null) is true, the Coalesce $obj->prop ?? null is correctly simplified to $obj->prop (since null is not an array). The property expression itself was narrowed to array<int>, but the object was not told that the property definitely exists. The isset() handler already did this by adding HasPropertyType to the object, but the Coalesce simplification path in createForExpr did not.

Test

Added tests/PHPStan/Analyser/nsrt/bug-11610.php with two cases:

  1. is_array($obj->prop ?? null) — the bug case, now correctly narrows to object{containers: array<int>}
  2. isset($obj->prop) || is_array($obj->prop) — already working, included for completeness

Fixes phpstan/phpstan#11610

… with null coalescing

- When is_array($obj->prop ?? null) narrows a Coalesce expression to its left side PropertyFetch, also add HasPropertyType constraint on the object
- This makes optional properties become required after type-checking through null coalescing
- New regression test in tests/PHPStan/Analyser/nsrt/bug-11610.php

Closes phpstan/phpstan#11610
@VincentLanglet VincentLanglet deleted the create-pull-request/patch-7gcsc5e branch April 11, 2026 15:40
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