How to verify that your code conforms to the coding standards

Coding standards or programming style describes a set of rules by convention to guide us how to write code. Basically, this set of rules describes how to format code regarding indentation, variable names, conditional sentences, etc.

This way the code of a project is more homogenized so it allows the people participating in a project easily understandable.

Drupal also has his own coding standard to develop and contribute modules. When we’re coding trying to follow this set of rules is really easy to forget to apply some and not realize that we are not compliying by some of the rules.

Fortunately Drupal provides a module that will help us to detect and even fix, in most cases, the coding standards that we’re not following. This module is called Coder.

Coder describes a set of coding standards rules(Drupal and DrupalPractice) to be used with the tool PHP_CodeSniffer, which is in charge to detect and fix the coding standard in various PHP standards as for example PSR1, PSR2, Zen, etc. But in our case we use the Drupal standard and we will make it work as follows:

Coder installation

As it is a tool that we use for all our Drupal projects we do a global installation with composer.

$ composer global require drupal/coder

PHP_CodeSniffer configuration

Add the Drupal and DrupalPractice coding standard rules in the PHP_CodeSniffer configuration using symbolic links:

$ ln -s ~/.composer/vendor/drupal/coder/coder_sniffer/Drupal ~/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/Drupal
$ ln -s ~/.composer/vendor/drupal/coder/coder_sniffer/DrupalPractice ~/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/DrupalPractice

To check that the tool is configured correctly should appear to us Drupal and DrupalPractice when executing:

$ phpcs -i

Run

Once we have it correctly configured we can check the coding standard of our files/folders:

$ phpcs –standard=Drupal web/modules/custom/module_example/module_example.module

phpcs display result

If we want to automatically fix these errors, we run:

$ phpcbf –standard=Drupal web/modules/custom/module_example/module_example.module

phpcbf display result

Conclusion

Certainly it is very profitable to apply the coding standards to get a cleaner code in our projects. And thanks to the Coder module together with the PHP_CodeSniffer tool the coding standard review process becomes a really simple task.

In addition, taking a bit more time, in many IDEs like PHPStorm or Sublime is possible to configure it for our comfort or also can be very useful in our continuous integration process but this will requires a new post in the future, stay tunned.

References