Drupal Coding Standards validation with PHP Code Sniffer and Github Actions

Published on 03 January, 2022

Drupal Coding Standards validation with PHP Code Sniffer and Github Actions

Web illustrations by Storyset

The article explains how to improve the Drupal development team's effectiveness and code quality by validating Drupal Coding Standards. You'll learn why the coding standards are essential and understand how to configure and run PHP Code Sniffer on each pull request.

Before diving into the automatic process, it makes sense to understand Drupal Coding Standards and why they are essential.

What are Drupal Coding Standards?

In general, coding standards are not more than rules proposed by the Drupal community and used for code formatting. The idea looks pretty straightforward, but it is beneficial. Here is a breakdown of how coding standards may help your organization or team.

  • Code Style. Just code formatting convention. It helps developers read other people's code easily and improves collaboration and code adoption.
  • Deprecated Functions. Helps identify the deprecated code as Drupal will remove it in the future. That is a pure investment in a developer's education.
  • Best Practises. Silently educates your development team to use the best Drupal practices. The simplest example could be using Dependency Injection instead of a global function call.
  • Documentation Automation. Helps to structure code comments properly to be converted into real documentation.

Why should your team follow Coding Standards?

In the long run, you'll save money and open opportunities.

For long-running projects, following coding standards plays a significant role as you open opportunities for having:

  • happy developers enjoying their work with the code
  • shorter delivery cycle for the features
  • automated code quality control
  • smoother transition to new software versions

Tools to check Drupal Coding Standards

First of all, let's say Drupal uses many technologies under the hood. Each language or markup may have its standards. In this article, we'd like to talk more about PHP and Drupal modules development (Drupal.org Coding Standards page).

  • PHP_CodeSniffer. Is the most popular tool to detect defined coding standard violations.
  • Coder. Drupal module has built-in support for Drupal coding standards and best practices for Drupal module development.

Enough theory! What if I tell you that you can set up Drupal Coding Standards checking on each Github Pull request in 5-10 minutes? Let's go!

Github Actions

GitHub Actions makes it easy to automate all your software workflows. In our case, we'll be checking the code provided in the pull request before passing it to the review phase. But, of course, in the ideal world, your developers should merge the code after passing all the checks.

Github php code sniffer checks passed

Github does its best to make Github Actions easy to try and use. Literarily, we need to create a single YAML file to make PHP Code Sniffer checking our code. Let's start!

Let's create a phpcs.yml file inside the .github/workflows directory.

name: PHP Code Sniffer

on: pull_request

jobs:
  phpcs:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Install PHP Code Sniffer
        run: |
          composer require --dev dealerdirect/phpcodesniffer-composer-installer
          composer require --dev drupal/coder

      - name: Check coding standards
        run: vendor/bin/phpcs

That should be enough for creating our first commit! Next, let's push the branch to Github and make a pull request. As a result, you should see that PHP Code Sniffer runs on each pull request. So do not worry if your Github action failed while installing PHP Code Sniffer in the directory with the existing composer.json file. We'll fix that later.

Github php code sniffer checks failed

PHP Code Sniffer configuration for Drupal

In the following example, we'll show you how to avoid conflicts and configure PHP Code Sniffer to use specific coding standards.

First, let's create the ci directory at the root of your repository and place the phpcs.xml file there. File directive should contain a relative path to the code you will check.

<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="phpcs">
    <description>PHP Code Sniffer configuration</description>
    <file>../web/modules/custom</file>
    <arg name="extensions"
         value="php,
                module,
                inc,
                install,
                test,
                profile,
                theme,
                css,
                info,
                txt,
                md,
                yml" />
    <config name="drupal_core_version"
            value="9" />
    <rule ref="vendor/drupal/coder/coder_sniffer/Drupal" />
    <rule ref="vendor/drupal/coder/coder_sniffer/DrupalPractice"/>
</ruleset>

PHP Code Sniffer will look in the current directory and all parent directories for a file called .phpcs.xml, phpcs.xml, .phpcs.xml.dist, or phpcs.xml.dist. If found, the sniffer will read configuration information from this file, including the files to check, the coding standard to use, and any command-line arguments to apply.

In our case, we are just telling PHP Code Sniffer to check only our custom modules directory.

We need to adjust the Github workflow's code to make our workflow fully work. Let's edit .github/workflows/phpcs.yml.

name: PHP Code Sniffer

on: pull_request

jobs:
  phpcs:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Install PHP CodeSniffer
        run: |
          cd ci
          composer require --dev dealerdirect/phpcodesniffer-composer-installer
          composer require --dev drupal/coder

      - name: Check coding standards
        run: |
          cd ci
          vendor/bin/phpcs

Now you should see PHP Code Sniffer installed and running checks on your custom modules directory. The output should break down errors, and warnings found.

FILE: ...upal/web/modules/custom/ScoreList/src/Form/ScoreListForm.php
----------------------------------------------------------------------
FOUND 2 ERRORS AND 1 WARNING AFFECTING 3 LINES
----------------------------------------------------------------------
 227 | ERROR   | [x] Functions must not contain multiple empty lines
     |         |     in a row; found 3 empty lines
 229 | ERROR   | [ ] More than 2 empty lines are not allowed
 273 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: 'preview-table'
----------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

It's probably a bad practice to check all the code trees with PHP Code Sniffer, as you'll quickly run out of your server's resources. However, it's enough to fit only custom code.

This article reveals only one possible way of coding standards validation. As the next step, you could explore IDE's possibilities for automated code checks.

When and how should I start doing the checks?

The general answer would be simple.

It's never late to start a cleanup of your code.

The best scenario would be to configure your coding standards checks before implementing the first feature.

If you already have a big codebase, it's probably better to have a little bit of planning. A lot of issues in the codebase could demotivate your team. Also, in our experience, people do not like to fix the problems introduced by others. So, here is a brief list of recommendations.

  • Development team should clearly understand the benefits of following coding standards.
  • Try to introduce automated checks in an agile way. For example, let's say, in the beginning, you could check only new code.
  • The whole team should agree on merging the code to avoid demotivating developers. But, unfortunately, it is not easy to make all the code-compliant in one moment.
  • Management should consider approving additional time for fixing initial issues.
  • Writing clean code should be a part of the team's culture.
  • Making your code open source could help developers be more responsible for their code.

Coding standards following is not a silver bullet or magic pill which solves all your current issues. However, discipline will help your team grow and deliver robust and maintainable solutions.

About the Author

About our team

Jet.Dev is a team of digital specialists who design, build and optimize digital solutions.

Since 2016, being a Drupal development company, the team has partnered with companies of all sizes, from startups to enterprises, to help them build appealing websites, robust web apps, and secure integrations.