In this tutorial i’m going to show you how you can run the PHP Code Beautifier and Fixer, or phpcf for short, from inside PhpStorm.
Having that all set, we need to tell PhpStorm where the CodeSniffer is installed. Go to Settings -> Tools -> External Tools. There we will create the configuration needed.
Click on the + icon. Fill the form with the following values:
- Name: the name you want to call it. This will be used to invoke the script through PhpStorm.
- Description: A short description of what the script does.
- Program: the path to phpcbf.
- Parameters: a list of parameters, will explain those later.
- Working directory: the variable $ProjectFileDir$ is used here.
Personally i created 3 sets of configurations. One to fix a single file, other to fix all php files in the current directory non-recursively, and another one to fix all php files in the current folder recursively. So let me show you the other 2 configs:
You can find a list of all parameters simply running phpcbf -h or you can go to PHP CodeSniffer documentation page. Here i’ll list the ones used in the examples above:
- –standard: The name or path of the coding standard to use.
- –extensions: A comma separated list of file extensions to fix (only valid if fixing a directory).
- -l: Local directory only, no recursion
And the variables:
- $FileDir$/$FileName$: parses the current file only.
- $FileDir$: parses the whole directory.
Here is the phpcbf in action:
After everything is setup, you can even assign keyboard shortcuts to run those scripts. Go to Settings -> Keymap:
Search for the ‘Name’ you inserted when created the link to the external tool phpcbf, click on the green pencil icon, and input the keyboard shortcut you want:
I hope this tutorial help you be more productive and make sure the code meet the WordPress Standards. Here’s some useful links:
- PHP CodeSniffer wiki
- Fixing Errors Automatically
- Automatically format code to match PSR standards with PhpStorm