PHP_CodeSniffer: Code Beautifier and Fixer, Symfony and PhpStorm

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 (PHP Code Beautifier and Fixer) script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

In this step by step tutorial I show you how I use this tools to setup my PhpStorm development environment.


Make sure composer bin is in your $PATH directory: check your current path with echo $PATH

Install PHP_CodeSniffer

If you use Composer, you can install PHP_CodeSniffer system-wide with the following command:
composer global require "squizlabs/php_codesniffer=*"

This will install PHP_CodeSniffer and all its dependencies into the ~/.composer/vendor/ directory and, most importantly, the PHP_CodeSniffer CLI tools are installed into ~/.composer/vendor/bin/.

See if the package is installed globally: composer global show

If you didn’t do it before, simply add ~/.composer/vendor/bin/ to your PATH in your ~/.bash_profile (or ~/.bashrc) like this:

export PATH=~/.composer/vendor/bin:$PATH

Now phpcs and phpcbf are now available on your command line:

phpcs -h

phpcbf -h

To keep your tools up to date, you simply do this:

composer global update

To remove a package, you edit ~/.composer/composer.json and then run composer global update.

Install Symfony code style

As described on the instructions here: Install the coding standard also system-wide:

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

Add Symfony code style:

~/.composer/vendor/bin/phpcbf --config-set installed_paths ~/.composer/vendor/escapestudios/symfony2-coding-standard

Check if code style installed:

~/.composer/vendor/bin/phpcbf -i

You should get something like:
The installed coding standards are PEAR, Zend, PSR2, MySource, Squiz, PSR1 and Symfony

Configure PhpStorm

Open the PhpStorm settings and go to Tools => External Tools, and add a new one with this config settings (change your username!):

Name: phpcbf single file
Description: Fix PHP Codesniffer warnings using PHP Code Beautifier and Fixer
Program: /Users/aidrissi/.composer/vendor/bin/phpcbf
Parameters: –report=full –report-file=$ProjectFileDir$/var/logs/phpcbf.log –standard=Symfony $FileDir$/$FileName$
Working directory:  $ProjectFileDir$

PhpStorm settings window: add new external tool

You can assign a keyboard shortcut for this new tool to format the current open document.

Open the settings again and navigate to: Keymap and search for phpcbf-single file and assign your preferred shortcut: In my case I use Command + Shift + B

PhpStorm run window: results of the run tool

Enjoy 🙂