|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types = 1); |
| 4 | + |
| 5 | +/** |
| 6 | + * Parse a PHPUnit clover XML report and fail if line coverage falls below |
| 7 | + * a threshold. Standalone script — no Composer/runtime dependency on a |
| 8 | + * coverage-check library, since the package itself is consumed as a static- |
| 9 | + * analysis library and adding a runtime dep for a single CI gate is overhead |
| 10 | + * without commensurate value. |
| 11 | + * |
| 12 | + * Usage: php bin/coverage-check.php <clover.xml> <threshold> |
| 13 | + */ |
| 14 | +$cloverPath = $argv[1] ?? null; |
| 15 | +$threshold = isset($argv[2]) ? (float) $argv[2] : null; |
| 16 | + |
| 17 | +if ($cloverPath === null || $threshold === null) { |
| 18 | + fwrite(\STDERR, "Usage: coverage-check.php <clover.xml> <threshold>\n"); |
| 19 | + exit(2); |
| 20 | +} |
| 21 | + |
| 22 | +if (!is_file($cloverPath)) { |
| 23 | + fwrite(\STDERR, "Clover report not found: {$cloverPath}\n"); |
| 24 | + exit(2); |
| 25 | +} |
| 26 | + |
| 27 | +$xml = simplexml_load_file($cloverPath); |
| 28 | + |
| 29 | +if ($xml === false) { |
| 30 | + fwrite(\STDERR, "Failed to parse clover XML: {$cloverPath}\n"); |
| 31 | + exit(2); |
| 32 | +} |
| 33 | + |
| 34 | +$metrics = $xml->project->metrics ?? null; |
| 35 | + |
| 36 | +if ($metrics === null) { |
| 37 | + fwrite(\STDERR, "No <project><metrics> element in clover XML\n"); |
| 38 | + exit(2); |
| 39 | +} |
| 40 | + |
| 41 | +$statements = (int) $metrics['statements']; |
| 42 | +$covered = (int) $metrics['coveredstatements']; |
| 43 | + |
| 44 | +if ($statements === 0) { |
| 45 | + fwrite(\STDERR, "No statements measured — cannot evaluate coverage\n"); |
| 46 | + exit(2); |
| 47 | +} |
| 48 | + |
| 49 | +$percent = ($covered / $statements) * 100.0; |
| 50 | + |
| 51 | +printf("Line coverage: %.2f%% (%d/%d) — threshold: %.2f%%\n", $percent, $covered, $statements, $threshold); |
| 52 | + |
| 53 | +if ($percent + 1e-9 < $threshold) { |
| 54 | + fwrite(\STDERR, "FAIL: line coverage below threshold\n"); |
| 55 | + exit(1); |
| 56 | +} |
| 57 | + |
| 58 | +echo "PASS\n"; |
| 59 | +exit(0); |
0 commit comments