如何配置PHP项目CI流水线在CRAP阈值违规时触发失败
在GitHub Actions中监控CRAP阈值并让流水线失败的方案
针对你在GitHub Actions中监控CRAP(Change Risk Anti-Pattern)阈值的需求,以下是两种可行的实现方案:
方案1:使用现成的Composer工具
借助第三方CLI工具解析PHPUnit生成的crap4j报告,在阈值违规时返回非零退出码,触发流水线失败。
步骤:
安装工具
在项目中通过Composer安装j6s/phpunit-crap-checker:composer require --dev j6s/phpunit-crap-checker配置PHPUnit生成crap4j报告
在phpunit.xml中添加日志配置,确保生成crap4j格式的报告:<phpunit> <!-- 其他配置 --> <logging> <log type="crap4j" target="build/crap4j.xml"/> </logging> </phpunit>在GitHub Actions中添加检查步骤
在CI workflow文件(如.github/workflows/ci.yml)中,在PHPUnit运行后添加CRAP检查步骤:jobs: ci: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up PHP uses: shivammathur/setup-php@v2 with: php-version: '8.2' coverage: xdebug # 需开启覆盖率才能计算CRAP - name: Install dependencies run: composer install --prefer-dist - name: Run PHPUnit with CRAP report run: phpunit --log-crap4j build/crap4j.xml - name: Enforce CRAP threshold run: ./vendor/bin/phpunit-crap-checker --threshold=30 build/crap4j.xml这里的
--threshold=30是预期的CRAP阈值,可根据项目调整。如果有方法的CRAP值超过该阈值,工具会返回非零状态码,GitHub Actions会自动标记流水线失败。
方案2:自定义PHP脚本检查
如果现成工具无法满足定制需求,可编写简单的PHP脚本读取crap4j报告并检查阈值。
步骤:
编写检查脚本
在项目根目录创建check-crap.php脚本:<?php if ($argc !== 3) { fwrite(STDERR, "Usage: php check-crap.php <threshold> <crap4j-report-path>\n"); exit(1); } $threshold = (int)$argv[1]; $reportPath = $argv[2]; if (!file_exists($reportPath)) { fwrite(STDERR, "Error: Report file not found at {$reportPath}\n"); exit(1); } $xml = simplexml_load_file($reportPath); $violations = []; foreach ($xml->xpath('//method') as $method) { $crapValue = (float)$method['crapValue']; if ($crapValue > $threshold) { $className = (string)$method->parent()->name; $methodName = (string)$method->name; $violations[] = "{$className}::{$methodName} (CRAP: {$crapValue})"; } } if (!empty($violations)) { fwrite(STDERR, "CRAP threshold exceeded (max allowed: {$threshold}):\n"); foreach ($violations as $violation) { fwrite(STDERR, "- {$violation}\n"); } exit(1); } echo "All methods pass CRAP threshold of {$threshold}\n"; exit(0);在GitHub Actions中调用脚本
修改CI workflow,在PHPUnit运行后添加脚本执行步骤:# ... 其他步骤 ... - name: Enforce CRAP threshold run: php check-crap.php 30 build/crap4j.xml
两种方案都能实现CRAP阈值监控,方案1适合快速集成,方案2适合需要自定义检查逻辑(比如排除特定文件/方法)的场景。
内容的提问来源于stack exchange,提问作者Aerendir
相关产品推荐
相关产品推荐

