Using the phpStorm Code Sniffer for WordPress
Although I’ve been using phpStorm for a while now I am only just discovering some of the benefits of the IDE. One of these is to be able to apply coding standards to projects where they are lacking.
Although there is documentation on the phpStorm site, it doesn’t directly apply to WordPress and the slight level of abstraction kept me from bothering to work it out until now.
First of all a bit about code sniffers. Code Sniffers are usually run from the command line and basically check the code for formatting and structural errors. A typical code sniffer command in a WordPress installation would be something like this:
phpcs --standard=WordPress wp-config.php
One does not need an IDE to use code sniffers and should you choose you can install it directly by following the instructions here.
If you happen to use phpStorm you can avoid the command line and have the IDE show you specifically where you are deviating from the standards.
The first thing to do is to make sure you have the PHP CodeSniffer available on your machine. You can either download it or you may already have it if you use VVV. When you find or install it go to the
phpcs executable file via the command line and type
phpcs --version. You should get the message:
PHP_CodeSniffer version <version> (stable) by Squiz Pty Ltd. (http://www.squiz.net)
Now you are ready to configure phpStorm to use it.
Go in to the Settings panel by typing
⌘, Then type Code Sniffer in the search box.
Set Configuration to Local and click on the little box with the dots and find your
phpcs executable file and select it. If you click on Validate you should get the same message you got from the command line.
Next, you will want to apply it to the code inspector and configure it to give you a warning. Type Inspections in the seach box of the Settings panel and it should come up under Editor. Under PHP choose PHP Code Sniffer Validation. It’s up to you to choose the appropriate severity but I prefer a simple warning.
Under the Severity you will see a box entitled Coding Standard and a refresh button. Here choose WordPress. If this option doesn’t appear you may need to download the WordPress Coding Standards and choose the path from the box with three dots.
Now you can restart phpStorm and you are all set to write beautiful code that follows WordPress Coding standards!
Please feel free to leave comments if there is anything I missed or if you need any clarification.