Dries Buytaert

Automating code checks in Drupal using Git Hooks

This page is part of my digital garden. It is more like a notebook entry than a polished blog post. It's a space where I document learnings primarily for my own reference, yet share them in case they benefit others. Unlike my blog posts, these pages are works-in-progress and updated over time. Like tending to a real garden, I periodically refine its content. I welcome suggestions for improvements at dries@buytaert.net.

I finally set up some Github pre-commit hooks on my local Drupal development environment.

Pre-commit hooks in Git can streamline your workflow by automating checks and tasks for every commit. The official documentation can be found at https://git-scm.com/docs/githooks.

If you, like me, often forget to run your code linter and static code analyzer, pre-commit hooks offer a great solution. They automate these tasks with every commit.

To set up a pre-commit hook, edit the file .git/hooks/pre-commit in your Drupal directory. Git specifically looks for a file named pre-commit in the .git/hooks directory so the name has to be exact.

Here is my current script:


# Execute PHP Code Beautifier and Fixer
if [ $? -ne 0 ]; then
 echo "Failed command: ./vendor/bin/phpcbf"
 exit 1

# Execute PHPStan for static code analysis
./vendor/bin/phpstan analyse –memory-limit=256M
if [ $? -ne 0 ]; then
 echo "Failed command: ./vendor/bin/phpstan analyse –memory-limit=256M"
 exit 1

The script runs phpcbf (PHP Code Beautifier and Fixer) for code formatting and phpstan (a static analysis tool for PHP) for identifying bugs. Should these tools find any issues, the commit is blocked.

Installing phpcbf and phpstan

Drupal does not ship with phpcbf or phpstan out-of-the-box, so these tools need to be installed. They can be installed individually using Composer:

$ composer require –dev squizlabs/php_codesniffer phpstan/phpstan

However, my recommended way to install these tools for Drupal is by installing the drupal/core-dev package. This package bundles a number of Drupal development tools and best practices, including phpcbf and phpstan.

$ composer require drupal/core-dev –dev –update-with-all-dependencies