Skip to content

Fix phpstan/phpstan#13023: function.alreadyNarrowedType and function.impossibleType after updates to 2.1.15#5184

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

Fix phpstan/phpstan#13023: function.alreadyNarrowedType and function.impossibleType after updates to 2.1.15#5184
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-b622qvo

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

When a trait method uses is_a($this, SomeClass::class), PHPStan analyzes the method once per class that uses the trait. This caused false positives: in the context of SomeClass it reported "always true" (function.alreadyNarrowedType), and in the context of SomeClass2 it reported "always false" (function.impossibleType). Both are incorrect since the trait code is shared across multiple classes.

Changes

  • Modified src/Rules/Comparison/ImpossibleCheckTypeHelper.php to treat $this as having uncertain type when inside a trait context, in both the sureTypes and sureNotTypes loops
  • Added regression test tests/PHPStan/Rules/Comparison/data/bug-13023.php
  • Added test method testBug13023 in tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php

Root cause

ImpossibleCheckTypeHelper::findSpecifiedType() compares the result type from the type specifier against the argument type from the scope. When analyzing a trait method, $this is typed as ThisType bound to the specific using class. The isSuperTypeOf check then returns a definitive yes/no for each class context, causing the rule to report false positives. The fix detects when we're in a trait and the expression being checked is $this, and treats the result as maybe instead.

Test

Added a regression test with a trait MyTrait used by both SomeClass and SomeClass2, where the trait method calls is_a($this, SomeClass::class). The test expects no errors.

Fixes phpstan/phpstan#13023

- When analyzing trait methods, $this is bound to each using class separately
- is_a($this, SomeClass::class) was reported as "always true" in SomeClass context
  and "always false" in SomeClass2 context, but both are false positives
- Added trait-aware check in ImpossibleCheckTypeHelper to treat $this as uncertain
  when inside a trait, since the same code is shared across multiple classes
- New regression test in tests/PHPStan/Rules/Comparison/data/bug-13023.php

Closes phpstan/phpstan#13023
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