Skip to content

[Php85] Skip by-ref arg and by-ref foreach on ArrayFirstLastRector - #9080

Merged
TomasVotruba merged 1 commit into
mainfrom
fix/array-first-last-skip-by-ref
Nov 27, 2026
Merged

TomasVotruba merged 1 commit into
mainfrom
fix/array-first-last-skip-by-ref

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Follow-up to #9079. ArrayFirstLastRector still rewrote array dim fetches that are written through a reference:

-sort($items[array_key_first($items)]);
+sort(array_first($items));

-foreach ($items[array_key_last($items)] as &$item) {
+foreach (array_last($items) as &$item) {

Both change behaviour: the by-ref arg gets "Only variables should be passed by reference" and sorts a temporary copy, the by-ref foreach modifies a temporary copy, so changes are lost silently.

Decoration is done in node visitors, not in the rule (rector.avoidFeatureSetAttributeInRector):

  • ByRefNodeVisitor marks IS_BYREF_VAR on the expr of a by-ref foreach, only when it is an ArrayDimFetch (variables keep their existing per function-like tracking).
  • CallLikeReflectionNodeVisitor marks IS_BYREF_VAR on an ArrayDimFetch arg passed to a by-ref parameter, reusing the resolved reflection and matchParameterReflection() (named + variadic). Reflection is resolved only when the dim fetch has a func call dim or var, to keep it off the common $a['key'] path.
  • ArrayFirstLastRector::shouldSkip() skips on IS_BYREF_VAR.

Added skip_by_ref.php.inc (func, method, static, named and variadic args, by-ref foreach) and by_value_arg.php.inc (by-value arg and foreach still change).

@TomasVotruba
TomasVotruba merged commit d4ff3fc into main Nov 27, 2026
51 checks passed
@TomasVotruba
TomasVotruba deleted the fix/array-first-last-skip-by-ref branch November 27, 2026 19:34
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