Created
January 5, 2018 13:53
-
-
Save joaoinacio/b54e6df696941d16d20aa2e71374f897 to your computer and use it in GitHub Desktop.
php QC 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/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