Skip to content

Instantly share code, notes, and snippets.

@ftassi
Forked from mardix/php-cs-fixer-pre-commit.php
Last active September 1, 2015 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftassi/7e26f773ad7975416d90 to your computer and use it in GitHub Desktop.
Save ftassi/7e26f773ad7975416d90 to your computer and use it in GitHub Desktop.
A pre-commit hook to make PHP code PSR-2 compliant, check for syntax error
#!/usr/bin/php
<?php
/**
* .git/hooks/pre-commit
*
* This pre-commit hooks will check for PHP error (lint), and make sure the code
* is PSR compliant.
*
* Dependecy: PHP-CS-Fixer (https://github.com/fabpot/PHP-CS-Fixer)
*
* @author Mardix http://github.com/mardix
* @since Sept 4 2012
*
*/
/**
* @param $file
*/
function lint($file)
{
$lintOutput = array();
exec("php -l " . escapeshellarg($file), $lintOutput, $return);
if ($return != 0) {
throw new \RuntimeException("Error validating PHP Syntax" . PHP_EOL . implode(PHP_EOL, $lintOutput) . PHP_EOL);
}
}
/**
* @param $file
*/
function phpCsFixer($file)
{
exec("php-cs-fixer fix --dry-run {$file} --fixers=long_array_syntax -v", $fixResult);
if ($fixResult[0] !== '.') {
$message = <<<T_START_HEREDOC
Error validating PHP Coding Standard for $file
You should run:
php-cs-fixer fix . --fixers=long_array_syntax
In order to fix the issue
T_START_HEREDOC;
throw new \RuntimeException($message);
}
}
/**
* collect all files which have been added, copied or
* modified and store them in an array called output
*/
exec('git diff --cached --name-only --diff-filter=ACM', $output);
foreach ($output as $file) {
/**
* Only PHP file
*/
if (pathinfo($file,PATHINFO_EXTENSION) == "php") {
try {
lint($file);
phpCsFixer($file);
} catch (\RuntimeException $e){
echo $e->getMessage();
exit(1);
}
}
}
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment