Skip to content

Instantly share code, notes, and snippets.

@cgmartin
Last active October 9, 2015 06:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cgmartin/3452087 to your computer and use it in GitHub Desktop.
Save cgmartin/3452087 to your computer and use it in GitHub Desktop.
ZF2 Git pre-commit hook
#!/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