I assume that you are already using git as version control system for php projects. It is true that sometimes we make some spelling mistake in the code which may cause a warning or a fatal error, But pushing the code that has error to production server may cause some serious problems. Or even committing the same code to your git repository may result in inconsistent git logs, for example a commit was made just to fix typos.

How to avoid it?

We are going to use PHP CodeSniffer that will inspect our code and show the warnings, errors or deprecated function usage before we commit the changes to git repository. This way the standard code practice becomes easier to follow.

Setup Git repo to use PHP Code Sniffer

Install additional required packages:
  • PEAR
  • PHP CodeSniffer

Install PHP PEAR package manager

Check if pear is installed on your system by running “pear version” on your terminal. If your do not see pear version, install pear on your system.

On Unix / Linux based distros

$ wget http://pear.php.net/go-pear.phar
$ php go-pear.phar

On Mac OS X

$ wget http://pear.php.net/go-pear.phar
$ php -d detect_unicode=0 go-pear.phar

or

$ curl -O http://pear.php.net/go-pear.phar
$ php -d detect_unicode=0 go-pear.phar

Install PHP CODE SNIFFER

Install PHP_CodeSniffer which is used run tests on our php code and checks for errors and code standards.

$ pear install PHP_CodeSniffer

Integrate php code sniffer with git

Lets configure the git repository to run php code sniffer on every git commit. Navigate to your php project directory and create a file “pre-commit” under .git/hooks

$ cd /path/to/project
$ vi .git/hooks/pre-commit

copy & paste below script and save it with ESC -> :wq

#!/bin/sh

PROJECT=`php -r "echo dirname(dirname(dirname(realpath('$0'))));"`
STAGED_FILES_CMD=`git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\\\.php`

# Determine if a file list is passed
if [ "$#" -eq 1 ]
then
    oIFS=$IFS
    IFS='
    '
    SFILES="$1"
    IFS=$oIFS
fi
SFILES=${SFILES:-$STAGED_FILES_CMD}

echo "Checking PHP Lint..."
for FILE in $SFILES
do
    php -l -d display_errors=0 $PROJECT/$FILE
    if [ $? != 0 ]
    then
        echo "Fix the error before commit."
        exit 1
    fi
    FILES="$FILES $PROJECT/$FILE"
done

if [ "$FILES" != "" ]
then
    echo "Running Code Sniffer..."
    ./vendor/bin/phpcs --standard=PSR1 --encoding=utf-8 -n -p $FILES
    if [ $? != 0 ]
    then
        echo "Fix the error before commit."
        exit 1
    fi
fi

exit $?

Important: make the pre-commit script executable by

$ chmod +x .git/hooks/pre-commit

Now your turn, After setting this up please do some commits with some intensional errors and Share your views.