Setting up coding standards for Drupal 8, 9 using phpcs
It is an important part of any framework or a language to maintain good coding standards.
Today we’ll see how to set it up for Drupal using phpcs.
You can pick and choose a variety of helper modules to achieve this task, but I find it fairly easy to use Coder.
Step 1
Install Coder to your project
composer require --dev drupal/coder
Step 2
Make sure coder has been downloaded into vendor directory
Type in vendor/bin/phpcs -i
from your console to verify.
You can also verify the phpcs file at vendor/bin/phpcs
directory
Step 3
Now that we know phpcs is working, we need to tell it to use Drupal coding standard checks instead of generic checks.
Download https://github.com/drupal-up/drupal_phpcs/blob/master/phpcs.xml file to your project's root.
Step 4
To properly make use of this file we need to make a few adjustments.
If you open up this file you can see that there is an element named <file> where we can set the folders we want to get checked.
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="phpcs-standard">
<description>Codestyle ruleset for Drupal</description>
<!-- Specify standards. -->
<rule ref="Drupal"/>
<rule ref="DrupalPractice"/>
<!-- Include path with the Drupal and DrupalPractice rules. -->
<config name="installed_paths" value="vendor/drupal/coder/coder_sniffer"/>
<!-- Set ignore extensions. -->
<!-- @todo remove .css to check also the css files. -->
<!-- @see https://www.drupal.org/node/2867601#comment-12075633 -->
<arg name="ignore" value="*.css,*.md,*.txt"/>
<!-- Specify folders. -->
<file>modules/contrib/shopify_buy_button</file>
<!-- <file>themes/custom</file> -->
</ruleset>
Set your directories there, for this example I’ve chosen modules/contrib/shopify_buy_button
module path by providing;
<file>modules/contrib/shopify_buy_button</file>
Step 5
Because we have defined the paths from the phpcs.xml file where we want to check for coding standards, we can simply execute vendor/bin/phpcs
You can also give additional arguments to this command if you choose to do so. vendor/bin/phpcs — help
will show you the accepted arguments.
Step 6
You can manually or automatically fix the issues given by Code-Sniffer.
To automatically fix them, simply execute vendor/bin/phpcbf
That’s all to it !
Resources
https://www.drupal.org/docs/develop/standards/coding-standards#helpermod
https://www.drupal.org/docs/contributed-modules/code-review-module/installing-coder-sniffer