PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

In Code Sniffer we can use different coding standards, for Drupal it's coder, that contain drupal coding standards and other best practices.

You can install Code Sniffer in two ways, with pear and with composer, in this article I will use composer.

All code provided below was tested on Ubuntu 16.04.

First of all install composer:

sudo apt-get update
sudo apt-get install curl php-cli php-mbstring git unzip
 cd ~
curl -sS https://getcomposer.org/installer -o composer-setup.php
php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
sudo chown -R  USERNAME:USERGROUP ~/.composer

Then install PHP codesniffer:

composer global require drupal/coder
composer global require dealerdirect/phpcodesniffer-composer-installer
set PATH $PATH $HOME/.composer/vendor/bin
phpcs -i

ln -s ~/.composer/vendor/drupal/coder/coder_sniffer/Drupal ~/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/Drupal
ln -s ~/.composer/vendor/drupal/coder/coder_sniffer/DrupalPractice ~/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/DrupalPractice

For testing that all works fine, you can run phpcs command, if it work correct, you will get path to codesniffer location

which  phpcs

> /home/USER_NAME/.composer/vendor/bin/phpcs

Copy result of this command.

Open PhpStorm and go to settings. Open "Languages & Frameworks → PHP → Code Sniffer", here set path to phpcs (for example - /home/USER_NAME/.composer/vendor/bin/phpcs). Press validate and if all is ok, you will get green message.

Image

Then go to "Editor → Inspections" and find "PHP Code Sniffer validation". Set this checkbox and select in Coding standard "Drupal".

Image

After this step phpcs setup is completed. Go to any php file and check errors highlighting.

 

Useful links: