composer require squizlabs/php_codesniffer
<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
<description>The coding standard for our project.</description>
<rule ref="PSR2"/>
<file>app</file>
<file>bootstrap</file>
<file>config</file>
<file>database</file>
<file>resources</file>
<file>routes</file>
<file>tests</file>
<exclude-pattern>bootstrap/cache/*</exclude-pattern>
<exclude-pattern>bootstrap/autoload.php</exclude-pattern>
<exclude-pattern>*/migrations/*</exclude-pattern>
<exclude-pattern>*/seeds/*</exclude-pattern>
<exclude-pattern>*.blade.php</exclude-pattern>
<exclude-pattern>*.js</exclude-pattern>
<!-- Show progression -->
<!-- <arg value="p"/>-->
</ruleset>
File > Settings > Editor > Inspections > PHP > Quality Tools > PHP Code Sniffer Validation
More info here: How to setup PHP Code Sniffer in PHPStorm
#!/bin/sh
SCRIPT_DISABLED=false
SHOW_PASSED_FILES=false
RULESET=./phpcs.xml # File with the phpcs settings
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".php\{0,1\}$")
if [ "$STAGED_FILES" = "" ] || $SCRIPT_DISABLED; then
exit 0
fi
PASS=true
echo "Validating PHPCS (Code Sniffer):"
# Check for phpcs
which ./vendor/bin/phpcs &> /dev/null
if [[ "$?" == 1 ]]; then
echo "\033[41mPlease install PHPCS before commit in this project:\033[0m"
echo "Run: composer require squizlabs/php_codesniffer"
exit 1
fi
for FILE in $STAGED_FILES
do
./vendor/bin/phpcs --standard="$RULESET" "$FILE"
if [[ "$?" != 0 ]]; then
echo "\033[41mPHPCS Failed: $FILE\033[0m"
PASS=false
elif $SHOW_PASSED_FILES; then
echo "\033[32mPHPCS Passed: $FILE\033[0m"
fi
done
echo '\nPHPCS validation finished.'
if ! $PASS; then
echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass PHPCS but do not. Please fix the PHPCS errors above and try again."
echo 'Tip: try to run the command "composer phpcbf"\n'
exit 1
else
echo "\n\033[42mPHPCS VALIDATION SUCCEEDED\033[0m\n"
fi
exit $?
- In the scripts section of
composer.json
"phpcs": "./vendor/bin/phpcs --standard=phpcs.xml",
"phpcbf": "./vendor/bin/phpcbf --standard=phpcs.xml",
"install-hooks": [
"cp pre-commit-hook.sh .git/hooks/pre-commit",
"chmod +x .git/hooks/pre-commit"
],
"pre-install-cmd": [
"@install-hooks"
],
"post-install-cmd": [
"@install-hooks"
]
Now when you run composer install
your pre-commit hook will be activated.
More infor about the steps 4 and 5, here: Setting up PHPCS and PreCommit Githooks to a Laravel Project
You can also use the Pre Commit Hook Pluginto use your pre-commit-hook.sh