How to convert traditional list syntax to short syntax across whole project?

Suppose I want to convert array traditional syntax to short syntax across multiple files in a project.

$myArray = array();

to

$myArray = [];

Pressing Ctrl + Enter on the array() keyword is only good for converting one usage, so for multiple usages across multiple files I can use Ctrl + Shift + Alt + i to bring up the Enter inspection by name box, and from there I can choose Traditional syntax array literal detected.

But in this case I want to convert traditional list syntax to short syntax, for example:

list($myVariable, $myOtherVariable) = ['thing1', 'thing2'];

to

[$myVariable, $myOtherVariable] = ['thing1', 'thing2'];

Unlike array short syntax, the inspection to detect and convert traditional list syntax does not seem to be available in the Ctrl + Shift + Alt + i list.

How can I convert to short list() syntax across multiple files at once in a project?

0

The inspections cannot do that, but a regex should work just fine.
In Replace in Files with the regex option enabled, try the following:

Search pattern: list[\s]*\(([\S\s][^\)]*)\)
Replace pattern: [$1]

https://recordit.co/ERSPYGMXm8

0
Avatar
Permanently deleted user

Thanks for the suggestion Eugene.

This is certainly helpful, but it is a bit too inclusive.

//a line like this will be changed just fine
list($myVariable, $myOtherVariable) = ['thing1', 'thing2'];

//but a line like this will also be affected
getWhitelist($something);
0

With regex, there's always something you've missed.
Please try this one instead: ((?<![A-z0-9]|\$|\-|\>)list[\s]*\(([\S\s][^\)]*)\)
I've added a negative lookbehind group that filters out list being a callable ($list()), being a part of a call (myList()/my-list()/my_list()), and being a method call ($a->list()).
If I've missed something again, you can add a character or a character class to the first group through the pipe.

0
Avatar
Permanently deleted user

Thank you for this response, Eugene. I have added a close parenthesis at the end of the pattern, and tested it using this snippet:

list($thing) = getOneThing();

list($foo, $bar) = getTwoThings();

getWhitelist();

Here are the results using search pattern  ((?<![A-z0-9]|\$|\-|\>)list[\s]*\(([\S\s][^\)]*)\)) and replacement pattern [$1]

[list($thing)] = getOneThing();

[list($foo, $bar)] = getTwoThings();

getWhitelist();

The search pattern seems right, but I'm still not sure how to replace properly.

0

@Matt

You have too many (). Just remove the outer one:

(?<![A-z0-9]|\$|\-|\>)list[\s]*\(([\S\s][^\)]*)\)

Or if you prefer to use original one, then use $2 for replacement (second/inner match):

((?<![A-z0-9]|\$|\-|\>)list[\s]*\(([\S\s][^\)]*)\))

[$2]

 

0

请先登录再写评论。