Skip to content

Instantly share code, notes, and snippets.

@nberard
Last active May 23, 2016 10:09
Show Gist options
  • Save nberard/a120fb6bc6c61b64de41eefa16da807c to your computer and use it in GitHub Desktop.
Save nberard/a120fb6bc6c61b64de41eefa16da807c to your computer and use it in GitHub Desktop.

Pre requisites

In order to work properly, it needs git, phpcs and phpcbf to be installed

Location of their bin can be provided with environment parameters (see source code)

To avoid committing code with check style issues, download the file and you can add a git hook on pre-commit:

ln -s /path/to/phpcs-pre-commit .git/hooks/pre-commit

If errors are found it will try to fix them with phpcbf if you agree

The standard to check against is PSR2 by default but can be overriden with STANDARD environment parameter

P.S.: /path/to/phpcs-pre-commit should be executable

chmod +x /path/to/phpcs-pre-commit
#!/bin/bash
## Location binaries
GIT_BIN=${GIT_BIN:-git}
PHPCS_BIN=${PHPCS_BIN:-./bin/phpcs}
PHPCBF_BIN=${PHPCBF_BIN:-./bin/phpcbf}
EXTENSIONS=${EXTENSIONS:-php}
STANDARD=${STANDARD:-PSR2}
STAGED_FILES=$($GIT_BIN diff --name-only --diff-filter=ACMR HEAD | grep \\.php | tr '\n' ' ')
ARGS="-n --standard=$STANDARD --encoding=utf-8 --extensions=$EXTENSIONS"
$PHPCS_BIN $ARGS $STAGED_FILES
if [[ $? -ne 0 ]]; then
echo -e "\e[31m✘ Errors were found\e[0m"
exec < /dev/tty
read -p "Do you want to try and fix them with phpcbf? [Y/n]" -n 1
if [[ ${REPLY:-y} =~ ^[Yy]$ ]]; then
$PHPCBF_BIN $ARGS $STAGED_FILES
$PHPCS_BIN $ARGS $STAGED_FILES
if [[ $? -ne 0 ]]; then
echo -e "\e[31m✘ Errors were still found, you need to fix them yourself!\e[0m"
fi
else
exit 1
fi
fi
exit 0
@datanel
Copy link

datanel commented May 19, 2016

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