Install Drupal Coder and PHP CodeSniffer to your Drupal project to lint PHP code

In the official Coder Sniffer install guide on Drupal.org, it recommends installing Coder and the Drupal code sniffs globally using the command:

composer global require drupal/coder

I don't particularly like doing that, because I try to encapsulate all project requirements within that project, especially since I'm often working on numerous projects, some on different versions of PHP or Drupal, and installing things globally can cause things to break.

So instead, I've done the following (see this issue) for my new JeffGeerling.com Drupal 8 site codebase (in case you haven't seen, I'm live-streaming the entire migration process!):

  1. Install the Coder module as a dev requirement, along with the Composer installer for PHP_CodeSniffer coding standards: composer require --dev drupal/coder dealerdirect/phpcodesniffer-composer-installer
  2. Verify the installation is working: ./vendor/bin/phpcs -i (should list Drupal and DrupalPractice in its output).

Once it's working, you can start using phpcs which was installed into the vendor/bin directory:

./vendor/bin/phpcs \
  --standard="Drupal,DrupalPractice" -n \
  --extensions="php,module,inc,install,test,profile,theme" \
  web/themes/jeffgeerling \
  web/modules/custom

GitHub Actions - PHPCS coding standards Coder review for Drupal

I also added a build stage to my site's GitHub Actions CI workflow which runs phpcs using the above command, to make sure my code is always up to snuff. You can see my phpcs GitHub Actions configuration here.

Happy coding!