Skip to content

[PHPStan] Add PreferGenericTemplateOnReturnedUnionParamRule to spot hidden generics - #8638

Merged
TomasVotruba merged 4 commits into
mainfrom
phpstan-hidden-generic-return-rule
Oct 12, 2026
Merged

TomasVotruba merged 4 commits into
mainfrom
phpstan-hidden-generic-return-rule

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Adds a self-analysis PHPStan rule that spots hidden generics: a method taking a class-type union param (e.g. New_|MethodCall) but declaring a broader single return type (their shared parent Node), then returning that very param. In such a case a @template generic narrows the return to the passed type instead of the broad parent.

Complements the existing PreferGenericTemplateOnSameUnionTypeRule, which only covers the case where both param and return are the same union. This one covers the broad-parent return.

Guards against false positives:

  • skips when a @template is already present
  • skips scalar unions
  • skips when the method does not return the param
  • skips when the return type is one of the union members (not a shared parent), e.g. a loop that reassigns the variable before returning

The rule found 3 real cases in the codebase, 2 of which are fixed here with @template generics:

  • RemoveNullTagValueNodeRector::processVarTagNull()
  • RemoveZeroBreakContinueRector::processVariableNum()

The third (SideEffectNodeDetector::resolveVariable()) is correctly skipped by the union-member guard.

@TomasVotruba
TomasVotruba force-pushed the phpstan-hidden-generic-return-rule branch 2 times, most recently from dfa2ff3 to b2bf1c3 Compare October 12, 2026 09:07
@TomasVotruba
TomasVotruba force-pushed the phpstan-hidden-generic-return-rule branch from b2bf1c3 to dd582dc Compare October 12, 2026 09:08
@TomasVotruba
TomasVotruba enabled auto-merge (squash) October 12, 2026 11:17
@TomasVotruba
TomasVotruba disabled auto-merge October 12, 2026 11:17
@TomasVotruba
TomasVotruba merged commit 002401c into main Oct 12, 2026
46 of 49 checks passed
@TomasVotruba
TomasVotruba deleted the phpstan-hidden-generic-return-rule branch October 12, 2026 11:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant