How to configure PHP_CodeSniffer with PhpStorm

Developers try to follow coding standards, but let’s face it: it is hard. Even harder for a team, when each Developer has a favorite coding standard. Because of this, it is a good idea to pre-define coding standards to create more readable and searchable code, and that’s what major PHP-based projects do (like WordPress and Symfony)

This is when PHP_CodeSniffer (phpcs for short) enters the picture to help analyze a PHP codebase.

How to install PHP_CodeSniffer

The preferred install method is using Composer; it can be installed system-wide:

$ composer global require "squizlabs/php_codesniffer=*"

or added as a project development dependency:

$ composer require "squizlabs/php_codesniffer=*" --dev

Integrate PHP_CodeSniffer with PhpStorm

First of all, load PHP_CodeSniffer into PhpStorm (the IDE usually loads the phpcs if it founds one). Go to Preferences > Languages & Frameworks > PHP > Quality tools

and click on the three-dotted button; in the new screen that pops up check the phpcs binary (the Validate button can be clicked to check it loads the expected phpcs binary)

Integrate a Coding Standard

There are phpcs coding standards (a/k/a ruleset) for almost every PHP-based project out there. For example, in this link can be found the Symfony one, and in this repository, there are instructions of how it can be included as a development dependency of a project:

$ composer require --dev escapestudios/symfony2-coding-standard:3.x-dev

Once added, in PhpStorm go to Preferences > Editor > Inspections, after that, in the middle panel go to PHP > Quality tools > PHP CodeSniffer validation, and finally in the third panel (the right one) select Custom from the Coding Standard list, and right after that click on the three-dotted button to load Symfony’s ruleset added as dependency of the project (it can be found in the vendor/escapestudios/symfony2-coding-standard/Symfony/ruleset.xml path)

Once that’s done, every time a PHP script is open it will be automatically analyzed by phpcs and it will show what the error is and how it can be fixed.

Hope this little how-to helps to improve the quality of your code.

Do you need some help?

Let's get started. Tell us a little about yourself and your organization
and we can start a conversation about your needs and our capabilities.

Related Posts