Forked from mardix/php-cs-fixer-pre-commit.php
Last active
September 1, 2015 13:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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