Check Drupal coding standard by phpcs in git pre-commit hook

10th Feb 2023
Check Drupal coding standard by phpcs in git pre-commit hook
Table of contents

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git. Git pre-commit validates Drupal coding standards on files before committing them and returns a message to fix each line of code on the files having errors.

>> Tìm hiểu, cài đặt và sử dụng PHP Code Sniffer

>> Source code dành cho ai cần MVC đi phỏng vấn

Follow the next steps to set up the pre-commit git hook with Drupal coding standards:

  1. Create hooks directory on root project.
  2. Create a pre-commit file in the hooks directory.
  3. Add the below pre-commit code to the hooks/pre-commit file.
#!/bin/bash

STANDARD="Drupal"
BIN="./vendor/bin"

echo
echo "Drupal Coder pre-commit hook – commit with the --no-verify option to skip the hook"
echo

# Check whether PHP_CodeSniffer can be found
if [ ! -f "$BIN/phpcs" ]
then
  echo "Drupal Coder not found – is it installed? 'composer require drupal/coder'"
  echo
  exit 1
fi

# Retrieve staged files
FILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD)

# Run the sniffer
echo "Running Drupal Coder."
echo
PHPCS=("$BIN/phpcs" "--standard=$STANDARD" "--filter=gitstaged" "--encoding=utf-8" "-p" ".")
"${PHPCS[@]}"

# Syntax Error
if [ $? != 0 ]
then
  echo "Please fix each violations detected."
  echo
  exit 1
fi

# Syntax OK
if [ $? == 0 ]
then
  echo "No violations detected"
  echo
  exit 0
fi

Add PHP commands on the scripts section of the composer.json file.

"scripts": {
      "post-install-cmd": [
          "php -r \"copy('hooks/pre-commit', '.git/hooks/pre-commit');\"",
          "php -r \"chmod('.git/hooks/pre-commit', 0755);\""
      ]
}

Now execute Composer install in your project directory

Composer install will mv hooks/pre-commit file to .git/hooks/pre-commit.

How to use it

git commit -m "The commit message."

This is going to execute Drupal Coder on each file and returns messages on the terminal in case of finding errors on files.

Bạn thấy bài viết này như thế nào?
1 reaction

Add new comment

Image CAPTCHA
Enter the characters shown in the image.

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.

Hướng dẫn từng bước set up một project PHP theo mô hình MVC. Bạn có thể sử dụng source này để tiết kiệm thời gian set up cho project của mình.