Skip to content

Instantly share code, notes, and snippets.

@pylebecq
Last active December 22, 2015 09:09
Show Gist options
  • Save pylebecq/6450295 to your computer and use it in GitHub Desktop.
Save pylebecq/6450295 to your computer and use it in GitHub Desktop.
Git pre-commit hook that checks the syntax of commited php files and runs the php-cs-fixer on them.
#!/usr/bin/env php
<?php
/**
* .git/hooks/pre-commit
*
* This pre-commit hooks will check for PHP error (lint), and make sure the code
* is PSR compliant.
*
* Dependency: PHP-CS-Fixer (https://github.com/fabpot/PHP-CS-Fixer)
*/
exec("pwd", $projectFolder);
$projectFolder = $projectFolder[0];
exec('git diff --cached --name-status --diff-filter=ACM', $output);
foreach ($output as $file) {
$fileName = trim(substr($file, 1) );
if (pathinfo($fileName,PATHINFO_EXTENSION) === "php" || pathinfo($fileName, PATHINFO_EXTENSION) === "twig") {
$lint_output = array();
exec("php -l " . escapeshellarg($fileName), $lint_output, $return);
if ($return == 0) {
exec("php-cs-fixer fix {$projectFolder}/{$fileName} --level=symfony; git add {$projectFolder}/{$fileName}");
} else {
echo implode("\n", $lint_output), "\n";
exit(1);
}
}
}
echo " OK.\n";
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment