Last active
December 19, 2024 03:44
-
-
Save cgmartin/3452087 to your computer and use it in GitHub Desktop.
ZF2 Git pre-commit hook
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/env php | |
<?php | |
/** | |
* .git/hooks/pre-commit | |
* | |
* This pre-commit hooks will check for PHP errors (lint), and make sure the | |
* code is PSR-2 compliant. | |
* | |
* Dependecy: PHP-CS-Fixer (https://github.com/fabpot/PHP-CS-Fixer) | |
*/ | |
$exit = 0; | |
/* | |
* collect all files which have been added, copied or | |
* modified and store them in an array called output | |
*/ | |
$output = array(); | |
exec('git diff --cached --name-status --diff-filter=ACM', $output); | |
foreach ($output as $file) { | |
if ('D' === substr($file, 0, 1)) { | |
// deleted file; do nothing | |
continue; | |
} | |
$fileName = trim(substr($file, 1)); | |
/* | |
* Only PHP files | |
*/ | |
$extension = pathinfo($fileName, PATHINFO_EXTENSION); | |
if (!preg_match('/^ph(p|tml)$/', $extension)) { | |
continue; | |
} | |
/* | |
* Check for parse errors | |
*/ | |
$output = array(); | |
$return = 0; | |
exec("php -l " . escapeshellarg($fileName), $output, $return); | |
if ($return != 0) { | |
echo "PHP file fails to parse: " . $fileName . ":" . PHP_EOL; | |
echo implode(PHP_EOL, $lintOutput) . PHP_EOL; | |
$exit = 1; | |
continue; | |
} | |
/* | |
* PHP-CS-Fixer | |
*/ | |
$output = array(); | |
$return = null; | |
exec("php-cs-fixer fix -v --dry-run --level=psr2 " . escapeshellarg($fileName), $output, $return); | |
if ($return != 0 || !empty($output)) { | |
echo "PHP file fails contains CS issues: " . $fileName . ":" . PHP_EOL; | |
echo implode(PHP_EOL, $output) . PHP_EOL; | |
echo " To fix, run:" . PHP_EOL; | |
echo " php-cs-fixer fix -v --level=psr2 " . escapeshellarg($fileName) . PHP_EOL; | |
$exit = 1; | |
continue; | |
} | |
} | |
exit($exit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment