Skip to content

Instantly share code, notes, and snippets.

@woozy
Created May 11, 2018 18:34
Show Gist options
  • Save woozy/6bafb17b8f124e3cf6f533515a25aee0 to your computer and use it in GitHub Desktop.
Save woozy/6bafb17b8f124e3cf6f533515a25aee0 to your computer and use it in GitHub Desktop.
Git hook to validate modified code against PSR-2 code standard
{
"require-dev": {
"squizlabs/php_codesniffer": "^3.2",
"exussum12/coverage-checker": "^0.10.0"
}
}
#!/usr/bin/env bash
# Based on code from http://tech.zumba.com/2014/04/14/control-code-quality/
PROJECT=$(php -r "echo dirname(dirname(dirname(realpath('$0'))));")
STAGED_FILES_CMD=$(git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\.php)
DIFF_SUFFIX="_diff"
PHPCS_SUFFIX="_phpcs.json"
declare -i ERROR_COUNTER=0
if [ "$#" -eq 1 ]
then
oIFS=$IFS
IFS='
'
SFILES="$1"
IFS=$oIFS
fi
SFILES=${SFILES:-$STAGED_FILES_CMD}
echo "Checking for errors PHP Lint..."
for FILE in $SFILES
do
php -l -d display_errors=0 $PROJECT/$FILE
if [ $? != 0 ]
then
echo "Fix your errors before commit!"
exit 1
fi
FILES="$FILES $PROJECT/$FILE"
done
if [ "$FILES" != "" ]
then
echo "Sniffing your code..."
TMP_DIR=/tmp/$(uuidgen)
mkdir -p $TMP_DIR
for FILE in $SFILES
do
mkdir -p $TMP_DIR/$(dirname $FILE)
git show :$FILE > $TMP_DIR/$FILE
git diff master $FILE > $TMP_DIR/$FILE$DIFF_SUFFIX
./vendor/bin/phpcs --standard=psr2 --report=json $TMP_DIR/$FILE > $TMP_DIR/$FILE$PHPCS_SUFFIX
./vendor/bin/diffFilter --phpcs $TMP_DIR/$FILE$DIFF_SUFFIX $TMP_DIR/$FILE$PHPCS_SUFFIX
PHPCS_ERROR=$?
ERROR_COUNTER=$ERROR_COUNTER+$PHPCS_ERROR
done
rm -rf $TMP_DIR
if [ $ERROR_COUNTER != 0 ]
then
echo "You code stinks. :P Fix your style before commit."
exit 1
fi
fi
exit $?
@anikale
Copy link

anikale commented Jan 1, 2019

Thanks!

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