Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pre-commit hook for git with phpcs and phpcbf (auto-correct obvious violations)
#!/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..."
./bin/phpcs --standard=PSR2 --encoding=utf-8 -n -p $FILES
if [ $? != 0 ]
then
echo "Coding standards errors have been detected. Running phpcbf..."
./bin/phpcbf --standard=PSR2 --encoding=utf-8 -n -p $FILES
git add $FILES
echo "Running Code Sniffer again..."
./bin/phpcs --standard=PSR2 --encoding=utf-8 -n -p $FILES
if [ $? != 0 ]
then
echo "Errors found not fixable automatically"
exit 1
fi
fi
fi
exit $?
@fdemiramon
Copy link
Author

fdemiramon commented May 12, 2015

  • Assumed that you have both phpcs and phpcbf in bin/ folder. Best practice is to use the dedicated package for phpcs: squizlabs/PHP_CodeSniffer
  • Copy / Paste that script in your .git/hooks folder and set correct rights to your new file:
chmod +x .git/hooks/pre-commit

@codehimanshu
Copy link

codehimanshu commented Nov 5, 2018

For Laravel, I had to change the command in the script to particular phpcs and phpcbf file inside vendor/bin folder.

@AnnaDamm
Copy link

AnnaDamm commented Mar 3, 2020

I recommend using xargs together with phpcbf and phpcs in case there is a really large number of files. Happened to me, when switching between code styles automatically. This will break the script with "Too many arguments" error:

echo $FILES | xargs --max-procs=4 ./bin/phpcbf -n -p

@h8every1
Copy link

h8every1 commented Mar 18, 2021

--max-procs=4 forces xargs to return no error code even if phpcs found some (MacOS Big Sur)

@AnnaDamm
Copy link

AnnaDamm commented Mar 23, 2021

then leave it out :-)
I would always do a phpcs after phpcbf, because you might only want to have an error code thrown when not all files could be fixed automatically and no error code when it was automatically fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment