Sail Knowledgebase

Running PHP Linter and PHP Code Sniffer on Deploy with Sail CLI

In this guide you will learn how to use Sail hooks to run the PHP linter and PHP Code Sniffer tools prior to deploying to production.

If you like Sail, consider sponsoring us via GitHub!

Install PHP and PHP Code Sniffer

You'll need to have a PHP binary available on your system, as well as the PHPCS binary to be able to lint PHP code and run the Code Sniffer on your local computer. You can install both using Homebrew:

brew install php-code-sniffer
brew install php

It is recommended to use the WordPress Coding Standards for PHPCS. You can download and install these from the official WordPress repository.

Create a pre-deploy executable

In your Sail project, create a new executable file in the .sail directory named pre-deploy:

touch .sail/pre-deploy
chmod +x .sail/pre-deploy

Sail CLI will run this executable every time you use the sail deploy command. You can have multiple pre-deploy hooks as well, Sail will run them all, as long as their file name starts with pre-deploy. (for example pre-deploy.php-lint).

Add the following code to the hook executable:

#!/bin/bash
FILES=`sail diff --raw | grep \.php$`
ROOT="$(dirname `dirname $0`)"
EXIST=''

for FILE in $FILES
do
    if [ -f "$ROOT/$FILE" ]; then
        EXIST="$EXIST $ROOT/$FILE"
    fi
done
FILES=$EXIST

echo "- Linting PHP files"
for FILE in $FILES
do
    php -l "$FILE" 1>/dev/null
    if [ $? != 0 ]; then
        exit 1
    fi
done

if [ "$FILES" != "" ]; then
    echo "- Running PHP Code Sniffer"
    phpcs --standard=WordPress -q -p $FILES
    if [ $? != 0 ]; then
        exit 1
    fi
fi

exit $?

This will grab a list of PHP files that have changed (with sail diff) and run each file through the PHP linter, and PHP Code Sniffer using the WordPress standard. If a lint or PHPCS check fails, it will use the exit code 1, which will abort the deploy:

$ sail deploy
# Deploying to production
- Running pre-deploy hooks
- Linting PHP files
- Running PHP Code Sniffer

FILE: /projects/saildemo.com/wp-content/themes/test/functions.php
-------------------------------------------------------------------------
FOUND 9 ERRORS AFFECTING 9 LINES
-------------------------------------------------------------------------
 50 | ERROR | [x] Expected 1 space after comma in argument list; 10 found
 51 | ERROR | [x] Expected 1 space after comma in argument list; 3 found
 52 | ERROR | [x] Expected 1 space after comma in argument list; 5 found
 ...

Note that if you'd like to deploy regardless of any errors raised by pre-deploy hooks, you can suppress them using:

sail deploy --skip-hooks

If you're stuck and need help with your local development environment setup, coding standards, unit testing, SCM integration, etc. please visit the getting help section.