Skip to content

Instantly share code, notes, and snippets.

@pedroresende
Forked from joaoinacio/PreCommitHook.php
Created February 2, 2018 10:55
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 pedroresende/2f85a93db61e1a68dc684003e8810e31 to your computer and use it in GitHub Desktop.
Save pedroresende/2f85a93db61e1a68dc684003e8810e31 to your computer and use it in GitHub Desktop.
php QC pre-commit hook
#!/usr/bin/php
<?php
/**
* Git pre-commit hook for PHP code quality
* install with `<path-to-file> install`
*/
class PreCommitHook
{
/**
* @var string[]
*/
protected $files;
public function __construct()
{
exec('git diff-index --cached --name-only HEAD', $files);
$this->files = $files;
}
public function install()
{
$this->testCommand('ln -s -r ' . escapeshellarg(__FILE__) . ' .git/hooks/pre-commit');
return 0;
}
public function testCommand($command)
{
exec($command, $output, $result);
if ($result !== 0) {
$this->failWithMessage($output, $result);
}
}
public function failWithMessage($message, $exitStatus = 1)
{
if (is_array($message)) {
$message = implode(PHP_EOL, $message);
}
echo $message;
exit(1);
}
public function getFiles($match = null)
{
if ($match === null) {
return $this->files;
}
$matchedFiles = [];
foreach ($this->files as $file) {
if (preg_match($match, $file)) {
$matchedFiles[] = $file;
}
}
return $matchedFiles;
}
}
$hook = new PreCommitHook();
if ($argc == 2 && $argv[1] == 'install') {
$hook->install();
exit();
}
echo 'Executing PHP Lint...' . PHP_EOL;
foreach ($hook->getFiles('/\.php$/') as $file) {
$hook->testCommand('php -l ' . escapeshellarg($file));
}
echo 'Executing PHP CS...' . PHP_EOL;
foreach ($hook->getFiles('/\.php$/') as $file) {
$hook->testCommand('vendor/bin/phpcs --extensions=php -n --standard=PSR2 ' . escapeshellarg($file));
}
echo 'Executing PHP STAN...' . PHP_EOL;
foreach ($hook->getFiles('/\.php$/') as $file) {
$hook->testCommand('vendor/bin/phpstan analyze --level=4 ' . escapeshellarg($file));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment