Skip to content

Rule Request: Convert Wrapping Callables to First-Class Callables #9400

@kojiromike

Description

@kojiromike

Summary

Add a new Rector rule to automatically convert arrow functions and closures that are simple wrappers around function/method calls into PHP 8.1+ first-class callable syntax.

Current Behavior

Rector has FirstClassCallableRector which converts array-based callables to first-class callable syntax:

// Before
$callable = [$this, 'method'];
// After
$callable = $this->method(...);

However, there's no rule to simplify arrow functions or closures that are simple wrappers.

Proposed Behavior

A new rule (e.g., CallableWrapperToFirstClassCallableRector that would convert:

// Example 1: Built-in function wrapper
- array_map(fn($x) => strlen($x), $items);
+ array_map(strlen(...), $items);

// Example 2: Static method wrapper
- array_filter($items, fn($x) => MyClass::validate($x));
+ array_filter($items, MyClass::validate(...));

// Example 3: Instance method wrapper
- array_map(fn($item) => $this->transform($item), $items);
+ array_map($this->transform(...), $items);

// Example 4: Multiple parameters
- usort($items, fn($a, $b) => strcmp($a, $b));
+ usort($items, strcmp(...));

// Example 5: Closure to first-class callable
- $callback = function ($x) { return strtoupper($x); };
+ $callback = strtoupper(...);

Conditions for Transformation

The rule should apply when:

  1. The arrow function/closure body contains a single callable
  2. The wrapper and inner callable signatures are the same
  3. Target PHP version is 8.1+

Implementation Suggestion

  • Set: Rector\Set\ValueObject\SetList::PHP_81 (or a new CodingStyle set)

Thanks for considering this idea as well as for all the hard work on rector. I'm not averse to trying to write this rule myself, but never having written a rule, I'd ask for feedback and guidance first.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions