Skip to content

Instantly share code, notes, and snippets.

@balintbrews
Last active August 29, 2015 14:04
Show Gist options
  • Save balintbrews/7caa457d8603c6265fe9 to your computer and use it in GitHub Desktop.
Save balintbrews/7caa457d8603c6265fe9 to your computer and use it in GitHub Desktop.
Sniff for the better — let's write Drupal code that rocks!

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.

  1. Install Composer:

     $ curl -sS https://getcomposer.org/installer | php
     $ mv composer.phar /usr/local/bin/composer`  
    
  2. Install PHP_CodeSniffer with Composer:

     $ composer global require squizlabs/PHP_CodeSniffer:\>=1.4.1
    
  3. 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.

  1. You have (hopefully) successfully installed PHP_CodeSniffer. Try it out:

     $ phpcs --version
    
  2. Download Coder module and place it to a centralized place, e.g. /usr/local/share.

  3. 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.

  1. 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.

  2. Enjoy your great new tool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment