-
Notifications
You must be signed in to change notification settings - Fork 0
/
PreCommit.php
executable file
·90 lines (74 loc) · 2.28 KB
/
PreCommit.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/php
<?php
require __DIR__.'/../../../vendor/autoload.php';
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Application;
class PreCommit extends Application
{
private $output;
private $input;
private $error = false;
public function __construct()
{
parent::__construct('', '');
}
public function doRun(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$files = $this->extractCommitedFiles();
$files = $this->filterNonPhpFiles($files);
$this->checkPhpSyntax($files);
$this->checkCodingStandards($files);
return (int) $this->error;
}
private function extractCommitedFiles()
{
$process = new Process("git diff --cached --name-only --diff-filter=ACMR");
$process->run();
return explode("\n", $process->getOutput());
}
private function filterNonPhpFiles($files)
{
return array_filter(
$files,
function ($file) {
return preg_match('/\.php$/', $file);
}
);
}
private function checkPhpSyntax($files)
{
foreach ($files as $file) {
$process = new Process(
"git show :$file | php -n -l -ddisplay_errors=1 -derror_reporting=E_ALL -dlog_errors=0"
);
$process->run();
if (!$process->isSuccessful()) {
$this->output->writeln(
sprintf('<error>Php syntax error at %s</error>', $file)
);
$this->error = true;
}
}
}
private function checkCodingStandards($files)
{
foreach ($files as $file) {
$process = new Process(
"git show :$file | php-cs-fixer fix --diff --fixers=-psr0 -"
);
$process->run();
if (!$process->isSuccessful()) {
$this->output->writeln(
sprintf('<error>Php Coding Standard error at %s</error>', $file)
);
$this->error = true;
}
}
}
}
$console = new PreCommit();
$console->run();