The user fabpot developed a tool, that automatically formats and rearranges your code according to PSR standards.
This blog post and tutorial will help you to install the tool, add it to PhpStorm and add a shortcut to perform a check to the currently opened file.
Step 1: Downloading and installing the tool
There are several ways to download and install the tool. However, I’ll show you the most easy way to do, which doesn’t require other tools like composer or homebrew to be installed.
We will use this cURL command
sudo curl http://get.sensiolabs.org/php-cs-fixer.phar -o /usr/local/bin/php-cs-fixer
to download and install the tool and then run this command
sudo chmod a+x /usr/local/bin/php-cs-fixer
to make it accessible globally.
If you prefer to install it via homebrew or composer, go to: https://github.com/fabpot/PHP-CS-Fixer#installation
Make sure, that it has been installed correctly by running
php-cs-fixer in your terminal
Step 2: Use it in PhpStorm
Go to PhpStorm and open the Settings/Preferences. Navigate to Tools -> External Tools and fill the form with these values
The most important part is the part „Tool settings“
This is what you need to enter:
Program: Path to php-cs-fixer
In my example, you’ll see that I’ve installed it via composer. If you’ve installed it via cURL your path should be different
—level=all —verbose —config=sf23 fix “$FileDir$/$FileName$”
If this throws you an error youse —level=psr2 instead of —level=all
Working Directory: $ProjectFileDir$
Step 3: Setting up a shortkey combination
and assign a keyboard shortcut to the command. I used „CTRL + CMD + ]“
Now, whenever you are in a file and want the code to be formatted, simply hit the keyboard shortcut and the tool should do the rest!