Drupal coding Standard and Best Practice | Drupal 8

Drupal coding Standard and Best Practice

Submitted by editor on Thu, 06/29/2017 - 13:05
Question

How to use phpcs and phpcbf to check and correct drupal 8 coding Standard ?

Create a Drupal 8 module is a good idea, but develop as Drupal is BEST.

The famous tools PhpCS and PhpCBF allow you to check and correct (some) drupal coding standards and best practice errors.

Install Drupal coder.

Step 1. Download drupal coder via drush (drush dl coder) or from https://www.drupal.org/project/coder and extract into a folder out side of the drupal project.
Here, for the example : /home/myhome/coder

Step 2. Download / Install additional packages using composer. (How to install composer)
Example:
cd /home/myhome/coder
composer update

Step 3. Configure envirenement.
Example:
export PATH="$PATH:/home/myhome/coder/vendor/bin"
set PATH $PATH /home/myhome/coder/vendor/bin
phpcs --config-set installed_paths /home/myhome/coder/coder_sniffer
phpcbf --config-set installed_paths /home/myhome/coder/coder_sniffer

Use PhpCS anf PhpCBF

-> Go to your custom module directory. Example : /var/www/drupal8/modules/custom/mymodule
You can use phpcs using absolute path of the module. But I got some errors when using phpcbf.
phpcs --standard=Drupal /var/www/drupal8/modules/custom/mymodule

Example of the Errors :
Array
(
[0] => Ignoring potentially dangerous file name /var/www/drupal8/modules/custom/mymodule.....
[1] => can't find file to patch at input line 3

Check drupal coding Standard errors

phpcs --standard=Drupal .
OR
phpcs --standard=Drupal /var/www/drupal8/modules/custom/mymodule

Correst some drupal coding Standard errors (Merked as [X])

phpcbf --standard=Drupal .
OR
# This may not work : To test
phpcbf --standard=Drupal /var/www/drupal8/modules/custom/mymodule

Check drupal Best Practice errors

phpcs --standard=DrupalPractice .
OR
phpcs --standard=DrupalPractice /var/www/drupal8/modules/custom/mymodule

Add new comment