-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathcoverage.php
More file actions
353 lines (295 loc) · 9.34 KB
/
Copy pathcoverage.php
File metadata and controls
353 lines (295 loc) · 9.34 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
<?php
/*
* Copyright (c) 2026 Netresearch DTT GmbH
* SPDX-License-Identifier: AGPL-3.0-only
*/
declare(strict_types=1);
/**
* E2E Coverage Collector
*
* This file collects PHP code coverage during E2E tests.
* Include this at the start of index.php when COVERAGE_ENABLED=1.
*
* Usage:
* 1. Set COVERAGE_ENABLED=1 and XDEBUG_MODE=coverage environment variables
* 2. Run E2E tests
* 3. Call GET /coverage.php?action=report to get coverage data
* 4. Call GET /coverage.php?action=clear to reset coverage
*
* Security: Only active when COVERAGE_ENABLED=1 environment variable is set.
*
* @see https://xdebug.org/docs/code_coverage
*/
// Coverage storage directory
define('COVERAGE_DIR', dirname(__DIR__) . '/var/coverage/e2e');
// Glob pattern matching all collected coverage files
define('COVERAGE_FILE_PATTERN', COVERAGE_DIR . '/*.json');
/**
* Check if coverage is enabled via environment variable.
*/
function isCoverageEnabled(): bool
{
return !empty($_SERVER['COVERAGE_ENABLED']) || !empty($_ENV['COVERAGE_ENABLED']);
}
/**
* Check if this is a direct request to coverage.php (handles nginx routing).
*/
function isDirectCoverageRequest(): bool
{
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
return str_starts_with(parse_url($requestUri, PHP_URL_PATH) ?? '', '/coverage.php');
}
// Handle coverage API requests (direct access to /coverage.php)
if (isDirectCoverageRequest()) {
if (!isCoverageEnabled()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['error' => 'Coverage not enabled. Set COVERAGE_ENABLED=1']);
exit;
}
handleCoverageRequest();
exit;
}
/**
* Start coverage collection for this request.
*/
function startCoverageCollection(): void
{
if (!function_exists('xdebug_start_code_coverage')) {
return;
}
if (!is_dir(COVERAGE_DIR) && !@mkdir(COVERAGE_DIR, 0755, true) && !is_dir(COVERAGE_DIR)) {
error_log('Coverage: Failed to create directory ' . COVERAGE_DIR);
return;
}
// Start collecting coverage with dead code analysis
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
// Register shutdown function to save coverage
register_shutdown_function('saveCoverageData');
}
/**
* Save coverage data at the end of the request.
*/
function saveCoverageData(): void
{
if (!function_exists('xdebug_get_code_coverage')) {
return;
}
$coverage = xdebug_get_code_coverage();
xdebug_stop_code_coverage();
if (empty($coverage)) {
return;
}
// Filter out dead code (-2) and non-src files before saving
$filteredCoverage = [];
foreach ($coverage as $file => $lines) {
if (!str_contains($file, '/src/')) {
continue;
}
$filteredLines = array_filter($lines, fn($hits) => $hits !== -2);
if (!empty($filteredLines)) {
$filteredCoverage[$file] = $filteredLines;
}
}
if (empty($filteredCoverage)) {
return;
}
// Generate unique filename using random bytes for better uniqueness
$uniqueId = bin2hex(random_bytes(16));
$filename = COVERAGE_DIR . '/coverage_' . $uniqueId . '.json';
$result = @file_put_contents($filename, json_encode($filteredCoverage, JSON_THROW_ON_ERROR));
if ($result === false) {
error_log('Coverage: Failed to write coverage file ' . $filename);
}
}
/**
* Handle coverage API requests.
*/
function handleCoverageRequest(): void
{
header('Content-Type: application/json');
$action = $_GET['action'] ?? 'status';
// Validate action parameter
if (!in_array($action, ['status', 'report', 'clear'], true)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid action. Use: status, report, clear']);
return;
}
switch ($action) {
case 'status':
$files = is_dir(COVERAGE_DIR) ? (glob(COVERAGE_FILE_PATTERN) ?: []) : [];
echo json_encode([
'enabled' => function_exists('xdebug_start_code_coverage'),
'xdebug_mode' => ini_get('xdebug.mode'),
'coverage_dir' => COVERAGE_DIR,
'files' => count($files),
]);
break;
case 'report':
$format = $_GET['format'] ?? 'clover';
if (!in_array($format, ['clover', 'json'], true)) {
$format = 'clover';
}
generateCoverageReport($format);
break;
case 'clear':
clearCoverageData();
echo json_encode(['status' => 'cleared']);
break;
default:
// Unreachable: $action is validated against the allow-list above.
http_response_code(400);
echo json_encode(['error' => 'Invalid action']);
break;
}
}
/**
* Generate coverage report from collected data.
*/
function generateCoverageReport(string $format): void
{
if (!is_dir(COVERAGE_DIR)) {
http_response_code(404);
echo json_encode(['error' => 'No coverage data found']);
return;
}
$mergedCoverage = mergeCoverageFiles();
if ($format === 'clover') {
header('Content-Type: application/xml');
echo generateCloverXml($mergedCoverage);
} else {
echo json_encode([
'files' => count($mergedCoverage),
'coverage' => $mergedCoverage,
]);
}
}
/**
* Merge all collected coverage files into one per-file line map.
*/
function mergeCoverageFiles(): array
{
$mergedCoverage = [];
$files = glob(COVERAGE_FILE_PATTERN) ?: [];
foreach ($files as $file) {
$data = readCoverageFile($file);
if ($data === null) {
continue;
}
foreach ($data as $filename => $lines) {
if (!is_array($lines)) {
continue;
}
$mergedCoverage[$filename] = mergeFileLines($mergedCoverage[$filename] ?? [], $lines);
}
}
return $mergedCoverage;
}
/**
* Read and decode a single coverage file, returning null on failure.
*/
function readCoverageFile(string $file): ?array
{
$content = @file_get_contents($file);
if ($content === false) {
error_log('Coverage: Failed to read file ' . $file);
return null;
}
$data = json_decode($content, true);
if (!is_array($data)) {
error_log('Coverage: Invalid JSON in file ' . $file);
return null;
}
return $data;
}
/**
* Merge the line hits of one coverage file into the already merged lines.
*/
function mergeFileLines(array $mergedLines, array $lines): array
{
foreach ($lines as $line => $hits) {
// Skip dead code
if ($hits === -2) {
continue;
}
if (!isset($mergedLines[$line])) {
$mergedLines[$line] = 0;
}
// Xdebug: 1 = executed, -1 = not executed but executable
if ($hits === 1) {
$mergedLines[$line] = 1;
} elseif ($mergedLines[$line] !== 1 && $hits === -1) {
$mergedLines[$line] = -1;
}
}
return $mergedLines;
}
/**
* Generate Clover XML format coverage report.
*/
function generateCloverXml(array $coverage): string
{
$timestamp = time();
$xml = new XMLWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('coverage');
$xml->writeAttribute('generated', (string) $timestamp);
$xml->startElement('project');
$xml->writeAttribute('timestamp', (string) $timestamp);
$xml->writeAttribute('name', 'timetracker-e2e');
$totalStatements = 0;
$coveredStatements = 0;
foreach ($coverage as $filename => $lines) {
$xml->startElement('file');
$xml->writeAttribute('name', $filename);
$fileStatements = 0;
$fileCovered = 0;
foreach ($lines as $line => $hits) {
$xml->startElement('line');
$xml->writeAttribute('num', (string) $line);
$xml->writeAttribute('type', 'stmt');
$xml->writeAttribute('count', $hits === 1 ? '1' : '0');
$xml->endElement();
$fileStatements++;
if ($hits === 1) {
$fileCovered++;
}
}
$xml->startElement('metrics');
$xml->writeAttribute('statements', (string) $fileStatements);
$xml->writeAttribute('coveredstatements', (string) $fileCovered);
$xml->endElement();
$xml->endElement(); // file
$totalStatements += $fileStatements;
$coveredStatements += $fileCovered;
}
$xml->startElement('metrics');
$xml->writeAttribute('statements', (string) $totalStatements);
$xml->writeAttribute('coveredstatements', (string) $coveredStatements);
$xml->writeAttribute('files', (string) count($coverage));
$xml->endElement();
$xml->endElement(); // project
$xml->endElement(); // coverage
return $xml->outputMemory();
}
/**
* Clear all coverage data.
*/
function clearCoverageData(): void
{
if (!is_dir(COVERAGE_DIR)) {
return;
}
$files = glob(COVERAGE_FILE_PATTERN) ?: [];
foreach ($files as $file) {
if (!@unlink($file)) {
error_log('Coverage: Failed to delete file ' . $file);
}
}
}
// Auto-start coverage if this file is included and coverage is enabled
if (!isDirectCoverageRequest() && isCoverageEnabled()) {
startCoverageCollection();
}