Loading ...

How to use phpcs and phpcbf as Composer scripts in your Drupal project

Submitted by Tim on September 20, 2021

If you follow the official guide on how to install Code Sniffer on Drupal.org, it recommends installing Coder globally through Composer.
This could however lead to problems if you are running multiple projects with different Drupal, PHP, Composer, ... versions.

Personally I rather install project specific packages into the project itself. So after looking up how Drupal itself does this regarding this issue on Drupal.org and finding others like the blogpost "Install Drupal Coder and PHP CodeSniffer to your Drupal project to lint PHP code" from Jeff Geerling, I combined both methods to have this installed as easy as it gets per project.

  1. Install the Coder module as a dev requirement, along with the PHP_CodeSniffer Standards Composer Installer Plugin
    composer require --dev drupal/coder dealerdirect/phpcodesniffer-composer-installer
  2. Add the phpcs & phpcbf scripts to your composer.json file
    ...
    "scripts": {
        ...
        "phpcs": "phpcs --standard='Drupal,DrupalPractice' --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer",
        "phpcbf": "phpcbf --standard='Drupal,DrupalPractice' --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer"
    },
    ...

    You can find more information about scripts in Composer at the Composer scripts documentation

Now you can just start using phpcs & phpcbf as composer commands like:

composer phpcs web/modules/custom