如何使用 pre-commit 钩子自动运行 PHPUnit 与 PHPCS?
解读
在国内 WordPress 外包或企业定制项目中,代码质量门禁已成为验收硬指标:甲方常要求“提交即检测、不通过即拒绝”。pre-commit 钩子能在本地 commit 阶段拦截不合规代码,提前暴露 PHPUnit 单测失败与 PHPCS 编码违规,避免推到 GitLab/Gitea 后触发 CI 再被打回,节省 Code Review 时间。面试官问此题,意在验证候选人是否具备“本地质量左移”意识,并能落地 Composer、脚本与钩子跨平台兼容的完整工程化方案。
知识点
- Git 钩子执行顺序:pre-commit → commit-msg → post-commit;pre-commit 若返回非 0 则终止提交。
- WordPress 官方编码规范:PHPCS 使用 WordPress-Core/WordPress-Docs/WordPress-Extra 三套规则,需通过
dealerdirect/phpcodesniffer-composer-installer自动注册路径。 - PHPUnit 在 WordPress 下的启动方式:
- 传统方式:安装
wp-phpunit/wp-phpunit并在tests/bootstrap.php中加载wp-tests-config.php。 - 现代方式:项目根提供
wp-config.php与phpunit.xml,通过composer scripts统一入口,屏蔽路径差异。
- 传统方式:安装
- 跨平台兼容:Windows 开发机需使用
#!/usr/bin/env sh并调用 Composer 脚本,避免直接写vendor/bin/phpunit路径导致 cmd 无法识别。 - 性能优化:pre-commit 只检测 暂存区(staged)文件,用
git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(php|js|css)$'过滤,减少全量扫描。 - 国内镜像加速:在
composer.json中配置repo.packagist.com或阿里云镜像,确保依赖安装速度,避免钩子因网络超时被跳过。 - Monorepo 场景:主题、插件、mu-plugins 分目录时,需在各自目录下放置
phpunit.xml与.phpcs.xml,钩子脚本里循环检测,保证增量范围与标准对应。
答案
步骤一:初始化项目规范
composer require --dev phpunit/phpunit wp-phpunit/wp-phpunit \
squizlabs/php_codesniffer wp-coding-standards/wpcs \
dealerdirect/phpcodesniffer-composer-installer
步骤二:根目录创建 .phpcs.xml
<?xml version="1.0"?>
<ruleset name="Project">
<description>WordPress 项目规范</description>
<rule ref="WordPress"/>
<file>./wp-content/plugins/your-plugin</file>
<file>./wp-content/themes/your-theme</file>
<arg value="ps"/>
</ruleset>
步骤三:创建 phpunit.xml
<phpunit bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="plugin">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
步骤四:在 composer.json 声明脚本
"scripts": {
"test": "phpunit",
"phpcs": "phpcs",
"phpcbf": "phpcbf"
}
步骤五:编写 scripts/pre-commit(Linux/Mac/Windows Git Bash 通用)
#!/usr/bin/env sh
STAGED=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(php)$')
if [ -z "$STAGED" ]; then
exit 0
fi
echo "Running PHPCS..."
composer run phpcs -- $STAGED
if [ $? -ne 0 ]; then
echo "PHPCS 未通过,请先执行 composer run phpcbf 修复或手动改正"
exit 1
fi
echo "Running PHPUnit..."
composer run test
if [ $? -ne 0 ]; then
echo "PHPUnit 单测失败,请修复后再提交"
exit 1
fi
步骤六:注册钩子
chmod +x scripts/pre-commit
git config core.hooksPath scripts
验证:修改插件文件 git add 后执行 git commit,若 PHPUnit 或 PHPCS 任一失败,提交即被阻断;全部通过才生成 commit。至此,本地质量门禁落地完成。
拓展思考
- 与 GitHub/Gitea Actions 协同:pre-commit 做轻量检测,只跑核心单测与 PHPCS;CI 端再做全量矩阵(PHP 7.4-8.3 + MySQL 5.7-8.0 + Nginx 缓存场景),形成双层门禁。
- 大项目加速:使用
phpcs --cache=.phpcs-cache与phpunit --cache-result-file=.phpunit.result.cache,结合git diff-base实现增量扫描,将 pre-commit 耗时控制在 5 秒内,避免开发者因等待而加--no-verify。 - Docker 统一环境:在
docker-compose.yml中提供wordpress-dev镜像,pre-commit 实际执行docker compose run --rm wp-cli composer run test,保证Windows、macOS、Linux 结果一致,消除“我本地能过”争议。 - 安全加固:在 pre-commit 中追加
npm run lint:js与npm run audit,防止第三方主题引入恶意 JavaScript;同时用secrets-detector扫描 AWS 密钥、私钥,阻断敏感信息进入仓库。