Skip to content

Instantly share code, notes, and snippets.

@softrebel
Forked from jwage/.php_cs
Created Feb 3, 2020
Embed
What would you like to do?
php-cs-fixer git pre commit hook
<?php
return Symfony\CS\Config\Config::create()
->level(Symfony\CS\FixerInterface::SYMFONY_LEVEL)
->fixers([
'short_array_syntax',
'ordered_use',
])
;
#!/usr/bin/env bash
ROOT="/path/to/your/code"
echo "php-cs-fixer pre commit hook start"
PHP_CS_FIXER="vendor/bin/php-cs-fixer"
HAS_PHP_CS_FIXER=false
if [ -x vendor/bin/php-cs-fixer ]; then
HAS_PHP_CS_FIXER=true
fi
if $HAS_PHP_CS_FIXER; then
git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | while read line; do
$PHP_CS_FIXER fix --config-file=$ROOT/.php_cs --verbose "$line";
git add "$line";
done
else
echo ""
echo "Please install php-cs-fixer, e.g.:"
echo ""
echo " composer require --dev fabpot/php-cs-fixer:dev-master"
echo ""
fi
echo "php-cs-fixer pre commit hook finish"
@softrebel
Copy link
Author

softrebel commented Feb 3, 2020

  1. First of all, install the php-cs-fixer development: composer require --dev fabpot/php-cs-fixer:dev-master"

  2. Then, create .php_cs file in root of your local repo:

<?php

return Symfony\CS\Config\Config::create()
    ->level(Symfony\CS\FixerInterface::SYMFONY_LEVEL)
    ->fixers([
        'short_array_syntax',
        'ordered_use',
    ])
;
  1. Then create pre-commit hook as bellow:
#!/usr/bin/env bash

echo "php-cs-fixer pre commit hook start"

PHP_CS_FIXER="php-cs-fixer"
HAS_PHP_CS_FIXER=false

if [ -x vendor/bin/php-cs-fixer ]; then
    HAS_PHP_CS_FIXER=true
fi

if $HAS_PHP_CS_FIXER; then
    FILES=` git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | tr '\n' ' '`
	if [ -z "$FILES" ]
	then
		  echo "no php file found to fix."
	else
		  $PHP_CS_FIXER fix --config=.php_cs --verbose ${FILES}
		  git add ${FILES}
	fi
else
    echo ""
    echo "Please install php-cs-fixer, e.g.:"
    echo ""
    echo "  composer require --dev friendsofphp/php-cs-fixer:dev-master"
    echo ""
fi

echo "php-cs-fixer pre commit hook finish"

Loading

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