Suggestion for “Extract closure” refactoring
We currently have “Extract method” refactoring, but sometimes I don't need the whole separate method. I'd like to have a closure instead, like when transforming code such as this:
foreach ($collection as $item) {
if ($item->property) {
/* … */
}
}
I usually simplify such a cycle by removing the inner ‘if’ and adding ‘array_filter’ on the collection before cycling, using ‘if’-condition as a filtering predicate. Right now, I have to make a closure by copying the condition and writing a closure around it manually, and then proceeding with filtering/removing the ‘if’.
I'd like to suggest a new “Extract closure” (or “Introduce closure”) refactoring, which would take selected code, show some dialog to sort external variables into parameters or imports, and replace selection with a call to a new closure variable (with an edit to give a new variable some name, like in “Introduce variable”). If called from inside a cycle, cycle variable(s) could be placed into parameter list by default. So if I select ‘$item->property’ in the above and click through the dialogs, I'd have code like this:
foreach ($collection as $item) {
$property = fn ($item) => $item->property;
if ($property($item)) {
/* … */
}
}
Where ‘$property’ can be easily moved out of cycle and used in filtering:
$property = fn ($item) => $item->property;
$filtered = array_filter($collection, $property);
foreach ($filtered as $item) {
/* … */
}
In this easy example, the closure could be then inlined, but sometimes it can be a bit unwieldy, so I'd leave it as a separate variable.
There are other cases where automated ‘extraction’ of a closure would help, so I'd love to see it added to PhpStorm. Or, if it can already be done with some existing refactorings, please explain me the process.
请先登录再写评论。
Hi,
Sounds like a nice idea for a feature request. You may submit one directly to our public tracker:
https://youtrack.jetbrains.com/newIssue