Features Releases

Refactor your code to functional style with PhpStorm 2018.1

How many times you wrote code like this to achieve a simple purpose?

Mapping values of an array:

$result = [];

foreach ($items as $key => $item) {
   $result[$key] = func($item);
}

Filtering:

$result = [];

foreach ($items as $key => $item) {
   if (condition($item)) {
       $result[$key] = $item;
   }
}

Or reducing an array to some value:

$acc = 0;

foreach ($numbers as $number) {
   $acc += $number;
}

The above code samples involve the imperative programming style, which is familiar to everybody. It has a certain flaw: we have to parse the code in our head and go through negligible but required details to understand it.

To solve this issue, PHP suggests relying on the built-in functions: array_map, array_filter, array_reduce, etc. These functions can improve readability and emphasize the intent of your code. Unfortunately, it’s not always clear when and how to apply them to the existing code, since in some cases details can be crucial.

To help you with the task, we are going to introduce automatic ways of transforming imperative code to functional equivalents via the corresponding inspections and quick fixes. Since there can be a lot of tricky cases and possible transformations, we’ve decided to start with the simplest case of the foreach to array_map transformation inspection and quick fix.

In PhpStorm 2018.1 EAP, you can find the new Loop can be converted to ‘array_map’ call inspection under Settings | Editor | Inspections | PHP | Code Style and apply the corresponding quick fix as usual, by pressing Alt + Enter.

array_map_3

Should you reconsider, the ‘array_map’ call can be converted to loop inspection and quick fix, which do exactly the opposite, are provided, too.

We’re going to add more transformations and cover more cases in the future.

What do you think about functional programming in PHP? What types of transformation do you find the most useful? Give us your opinions in the comments or tweet @phpstorm!

Your JetBrains PhpStorm Team
The Drive to Develop

image description