Skip to content

[PHPStan] Add rule to hoist resolveClassReflection() above foreach in Rector rules - #8758

Merged
TomasVotruba merged 2 commits into
mainfrom
phpstan-no-resolve-class-reflection-in-foreach
Oct 21, 2026
Merged

TomasVotruba merged 2 commits into
mainfrom
phpstan-no-resolve-class-reflection-in-foreach

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Inside a Rector rule, resolveClassReflection($node) returns the single refactored class, which is identical on every loop iteration. Calling it inside a foreach() is wasted work - it should be hoisted above the loop.

This adds a custom PHPStan rule NoResolveClassReflectionInForeachRule that flags such calls. It is scoped to classes implementing RectorInterface, so legitimate per-iteration resolution elsewhere (e.g. resolving a different class per statement) is not touched.

Applied the hoist to the 3 Rector rules it flagged:

  • RemoveUnusedPrivateClassConstantRector
  • PropertyTypeFromStrictSetterGetterRector
  • TypedPropertyFromAssignsRector

TomasVotruba and others added 2 commits October 22, 2026 00:12
… Rector rules

The refactored class reflection is identical for every loop iteration, so resolving it inside a foreach() in a Rector rule is wasted work. New rule flags it; applied the hoist to 3 existing rules.
@TomasVotruba
TomasVotruba merged commit 7e5bf44 into main Oct 21, 2026
49 checks passed
@TomasVotruba
TomasVotruba deleted the phpstan-no-resolve-class-reflection-in-foreach branch October 21, 2026 22:15
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.

2 participants