Installing Drupal 7’s Coder and PHP Codesniffer on MAMP

If you need to check coding standards for your Drupal 7 custom module, there is no better way than using the Coder module with PHP CodeSniffer. Unfortunately if you are using MAMP, and using the PHP executable provided by MAMP, the installation becomes a little more complicated.

Here’s how to install the required modules.

Install Coder

Coder module should be installed in the global Drush directory, rather than in a website’s directory. The Drush directory should be  ~/.drush .

$ cd ~/.drush
$ drush dl coder
$ # Refresh Drush cache to access new commands.
$ drush cc drush

Use MAMP’s PHP for Drush

Assume you are running MAMP’s PHP for Drush. This is done by setting the environment variable DRUSH_PHP to MAMP’s PHP executable with the correct version. This is done by adding in ~/.bashrc or ~/.bash_profile :

# In ~/.bashrc
# Use the path leading to the version of PHP you want to use in MAMP.
export DRUSH_PHP=/Applications/MAMP/bin/php/php5.6.7/bin/php

Installing PHP CodeSniffer

PHP CodeSniffer is a PEAR module.

Go to MAMP’s PHP directory and run the pear executable there, for example:

$ cd /Applications/MAMP/bin/php/php5.6.7/bin
$ # Coder 7.x is only compatible with PHP CodeSniffer 1.x and not the latest PHP CodeSniffer 2.x
$ # See https://www.drupal.org/node/2342611
$ # Install the latest 1.x version of PHP CodeSniffer.
$ ./pear install PHP_CodeSniffer-1.5.6

Then add Drupal coding standards to the PHP CodeSniffer directory:

$ cd /Applications/MAMP/bin/php/php5.6.7/lib/php/PHP/CodeSniffer/Standards
$ # Symlink to Drupal coding standards provided by Coder.
$ ln -s ~/.drush/coder/coder_sniffer/Drupal Drupal

Set up phpcs command

Coder makes use of the phpcs command to use PHP CodeSniffer. Make sure you can run phpcs on the command line, by setting an alias in ~/.bashrc or ~/.bash_profile .

# In ~/.bashrc
# alias phpcs=/Applications/MAMP/bin/php/php5.6.7/bin/phpcs

Test the installation

Test it by using the drush drupalcs command on a PHP file or a module file, for example:

$ # Check code standards for test PHP file.
$ drush drupalcs /Applications/MAMP/htdocs/test.php
$ # Check code standards for a custom module.
$ drush drupalcs /Applications/MAMP/htdocs/public_html/sites/all/modules/custom/mymodule/mymodule.php

All done!

See also: Other methods of installation

There are other ways to install PHP CodeSniffer but they may not work for this configuration which uses MAMP’s PHP.

In particular, the command drush install-php-code-sniffer may not work for you even if you installed Coder through Drush.

The code for this command is in the function drush_coder_review_install_php_code_sniffer() in the file ~/.drush/coder/coder_review/coder_review.drush.inc .

Leave a Reply

Your email address will not be published. Required fields are marked *