Great developers write great code that is not only great, but also follows the coding standards of the framework/language they use. We are great developers!
Today I'm challenging you that from now on, you only push code that follows Drupal's coding standards. But instead of asking you to learn and remember all those boring rules, I suggest you a great tool. PHP_CodeSniffer for the rescue! It is a PHP script that detects violations of a defined coding standard in your code. Coder module for Drupal is kind enough to define those standards for us.
Setting it up is really simple. There are many ways to install and use PHP_CodeSniffer. I'm going to share my favorite approach, which, I believe, is the most simple and straightforward way.
-
Install Composer:
$ curl -sS https://getcomposer.org/installer | php $ mv composer.phar /usr/local/bin/composer`
-
Install PHP_CodeSniffer with Composer:
$ composer global require squizlabs/PHP_CodeSniffer:\>=1.4.1
-
Composer places the binaries under ~/.composer/vendor/bin. Make sure you include this folder in your path.
Edit your
.bash_rc
or.bash_profile
and add the following:export PATH="$HOME/.composer/vendor/bin:$PATH"
If you already have a line that starts with export PATH
, just add in the $HOME/.composer/vendor/bin
part, using :
as a delimiter. Make sure you do $ source .bashrc
or $ source .bash_profile
in order to get your changes applied.
-
You have (hopefully) successfully installed PHP_CodeSniffer. Try it out:
$ phpcs --version
-
Download Coder module and place it to a centralized place, e.g.
/usr/local/share
. -
To check all files within a folder, run the following command (change the path to the Drupal sniffs depending on your installation):
phpcs --standard=/usr/local/share/coder/coder_sniffer/Drupal .
You can supply the name of the file(s), name of folder(s), just like anything you would pass to a Unix command that works with files and folders.
-
Create an alias, so you don't have to type that long command ever again.
Put this into your
.bashrc
or.bash_profile
file (change the path to the Drupal sniffs depending on your installation):alias drupalcs="phpcs --standard=--standard=/usr/local/share/coder/coder_sniffer/Drupal"
Make sure you do
$ source .bashrc
or$ source .bash_profile
in order to get your changes applied. -
Enjoy your great new tool!