My PHP Git Hooks
2020-04-11 21:30:00 +0000 UTCGit hooks are a great way to stop you from doing something you do not want to do. Here is how I set my git hooks for PHP projects.
Pre Commit
To stop myself from committing code that still contains debug messages i.e
calls to echo
, print
, print_r
etc. I use PHP
CodeSniffer with a custom
configuration for a pre commit run.
If I really do want to commit with the functions still live in the code there are 2 options.
- Commit with
git commit -n
, this is the no verify flag that will skip the pre-commit hook. - Add a comment in the code above the line with the function call
//phpcs:ignore
CodeSniffer config
.git/hooks/phpcs_pre_commit.xml
<?xml version="1.0"?>
<ruleset name="Pre Commit" namespace="Tom\PreCommit">
<description>Dont let me commit this</description>
<rule ref="Generic.PHP.ForbiddenFunctions">
<properties>
<property name="forbiddenFunctions" type="array">
<element key="delete" value="unset"/>
<element key="print" value="null"/>
<element key="echo" value="null"/>
<element key="print_r" value="null"/>
<element key="var_dump" value="null"/>
<element key="create_function" value="null"/>
</property>
</properties>
</rule>
</ruleset>
Git Hook Script
.git/hooks/pre-commit
Ensure to set this file executable.
#!/bin/bash
set -e
root_dir=$(pwd)
for file in $(git diff --name-only --cached); do
if [[ -f $file ]]; then
#root_dir=$(cd $(dirname "${file}") && git rev-parse --show-toplevel)
config="${root_dir}/.git/hooks/phpcs_pre_commit.xml"
phpcs --report=emacs --standard="${config}" "${file}"
fi
done;
Pre Push
Before I push code upstream I want to ensure the tests (phpunit) are still passing.
To not trigger this check I can run git push --no-verify
.
Git Hook Script
.git/hooks/pre-push
Ensure to set this file executable.
#!/bin/bash
set -e
./vendor/bin/phpunit tests
Short and sweet.