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?
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
- Specifying the path to PHP Code Sniffer:
- Go to Project Settings | PHP | Code Sniffer
- Set path to [User directory]/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs (replace [User directory] with value from above)
- Adjust the other values as you please.
- Configure PHP Code Sniffer as a PhpStorm inspection
- Go to Editor | Inspections
- Enable "PHP Code Sniffer validation"
- 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?
You can also check code styles for the entire project
To run PHP Code Sniffer in "batch mode," do the following:
- Using the menus, go to Code | Inspect code…
- Click on the ... button to customize the inspection profile
- Click on the cog next to the Profile select element
- Select Duplicate and give your new profile a custom name, e.g. "Only PHP CS"
- Uncheck all inspections except for PHP | PHP Code Sniffer validation
- Click on OK
- 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.
I used this article as a basis to get Code Sniffer installed.