Skip to content

Fix phpstan/phpstan#11844: Invalid property.unusedType report for nullable WeakMap property (broken since 1.12.4)#5316

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

Fix phpstan/phpstan#11844: Invalid property.unusedType report for nullable WeakMap property (broken since 1.12.4)#5316
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-6jv47zv

Conversation

@phpstan-bot
Copy link
Copy Markdown
Collaborator

Summary

Fixes a false positive property.unusedType error when a nullable generic property (e.g., ?WeakMap) is assigned new WeakMap() inside a null check like if ($this->map === null). This regression was introduced in 1.12.4 by PR #3364.

Changes

  • Modified src/Analyser/ExprHandler/NewHandler.php to resolve the declared property type from reflection instead of using the scope-narrowed type
  • Added resolveAssignedPropertyDeclaredType() helper method that handles both instance and static property fetches
  • Added regression test tests/PHPStan/Rules/TooWideTypehints/data/bug-11844.php covering static properties, instance properties, and direct assignment

Root cause

When new WeakMap() is assigned to a property inside a null check (if ($this->map === null)), the scope has already narrowed the property type to null. The NewHandler::exactInstantiation() method used $scope->getType($assignedToProperty) to infer generic types from the property, but this returned the narrowed type (null) instead of the declared type (WeakMap<object, string>|null). After TypeCombinator::removeNull(), this became never, causing TooWideTypeCheck to incorrectly conclude that WeakMap<object, string> was never assigned.

The fix resolves the property reflection directly and uses getReadableType() to get the declared type, which is unaffected by scope narrowing.

Test

Added tests/PHPStan/Rules/TooWideTypehints/data/bug-11844.php with three test cases:

  • Static nullable WeakMap property assigned inside null check (original report)
  • Instance nullable WeakMap property assigned inside null check
  • Direct assignment without null check (was already working)

All three should produce zero property.unusedType errors.

Fixes phpstan/phpstan#11844

…eric property assigned inside null check

- Used declared property type from reflection instead of scope-narrowed type in NewHandler
- When `new WeakMap()` was assigned inside `if ($this->map === null)`, scope returned narrowed `null` type
- TypeCombinator::removeNull on `null` yielded `never`, making TooWideTypeCheck think WeakMap was never assigned
- New regression test in tests/PHPStan/Rules/TooWideTypehints/data/bug-11844.php
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.

1 participant