How to Use Code Sniffer in PHPStorm (for Mac OS)

What is Code Sniffer?

If you work with other developers or contribute your code back to the Drupal community, coding standards are important to follow. Read this excellent post if you want to know more about the virtues of using coding standards.

How can I check my code?

My local development environment consists of MAMP and PHPStorm.

You can get PHPStorm to automatically check your code against Drupal's coding standards. And it's pretty simple to set up.

Below are the steps I took.

Open terminal and enter the following commands:

composer global require 'squizlabs/php_codesniffer=2.7.0'
composer global require 'drupal/coder=^8.2'

cp -r ~/.composer/vendor/drupal/coder/coder_sniffer/* ~/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards

# This is your [User directory] which will be used later on:
echo ~

Keep in mind that version 3 of php_codesniffer doesn’t work with coder, and that version 8 of coder is required for php_codesniffer 2.x.

Enable PHP Code Sniffer integration in PhpStorm

  1. Specifying the path to PHP Code Sniffer:
    1. Go to  Project Settings | PHP | Code Sniffer
    2. Set path to [User directory]/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs (replace [User directory] with value from above)
    3. Adjust the other values as you please.
  2. Configure PHP Code Sniffer as a PhpStorm inspection
    1. Go to Editor | Inspections
    2. Enable "PHP Code Sniffer validation"
    3. Select "PHP Code Sniffer validation" and configure "Coding Standard" to "Drupal" (You  might have to click on the ... button next to the drop down menu to refresh the options)

Now that I have it installed, how do I use it?

The results of running the PHP Code Sniffer validation inspection will immediately be visible in the editor when opening a PHP, JavaScript or CSS file. Just like regular PhpStorm inspections, warnings and errors that were captured by PHP Code Sniffer will be shown in the right gutter and as tooltips inside your code.

You can also check code styles for the entire project

To run PHP Code Sniffer in "batch mode," do the following:

  1. Using the menus, go to Code | Inspect code…
    1. Click on the ... button to customize the inspection profile
    2. Click on the cog next to the Profile select element
    3. Select Duplicate and give your new profile a custom name, e.g. "Only PHP CS"
    4. Uncheck all inspections except for PHP | PHP Code Sniffer validation
    5. Click on OK
    6. Click on OK once more to start

You can skip steps a. through e. in the future and simply select "Only PHP CS" from the "Inspection profile" select element.

Happy coding.

I used this article as a basis to get Code Sniffer installed.