Skip to content

Instantly share code, notes, and snippets.

@chrisyue
Last active November 17, 2017 09:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisyue/9427800 to your computer and use it in GitHub Desktop.
Save chrisyue/9427800 to your computer and use it in GitHub Desktop.
pre-commit for php,使用 php -l / phpmd / php-cs-fixer做检查,需要在项目根目录添加phpmd.xml,.php_cs文件
#!/usr/bin/env php
<?php
// 使用 php -l / phpmd / php-cs-fixer做检查,需要在项目根目录添加phpmd.xml(如果使用phpmd),.php_cs(如果使用phpcs并且有自定义的配置)文件
// 使用前执行 chmod +x path/to/pre-commit
exec('git diff HEAD --name-only --diff-filter=AMRC', $filenames);
$filenames = array_filter($filenames, function($filename) {
return pathinfo($filename, PATHINFO_EXTENSION) === 'php';
});
$exitCode = 0;
foreach ($filenames as &$filename) {
$filename = escapeshellarg($filename);
exec("php -l $filename", $output, $lintExitCode);
if (0 !== $lintExitCode) {
$exitCode = 1;
}
}
// 如果不需要phpmd,以下代码可以删除
system(sprintf('phpmd %s text phpmd.xml', implode(',', $filenames)), $phpmdExitCode);
if (0 !== $phpmdExitCode) {
$exitCode = 1;
}
// 如果不需要phpcs,以下一行可以删除
system("php-cs-fixer fix .; git add .");
exit($exitCode);
@supgeek-rod
Copy link

这个文件怎么用呢?

@chrisyue
Copy link
Author

@supgeek-rod 放在项目目录/.git/hook/pre-commit文件里就行,注意pre-commit文件的运行权限,必须要

chmod +x pre-commit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment