Files
errors.bitreport.pt/clients/php/ErrorReporter.php
nelson-baptista 836d967aeb
CI / Test ingest-api (pull_request) Successful in 33s
CI / Test api (pull_request) Successful in 34s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m19s
CI / Validate Docker build (pull_request) Successful in 3m54s
chore(runtime): BIT-31723 upgrade Node 20 → Node 24 LTS + audit PHP/TS code
- Dockerfiles (admin-ui, collector-worker, ingest-api): node:20-bookworm-slim → node:24-bookworm-slim
- CI (.gitea/workflows/ci.yml): node-version '20' → '24' in all 3 jobs
- package.json engines.node: '>=20' → '>=24.22.1' (admin-ui, api, collector-worker, ingest-api, web)
- @types/node: ^20/^22 → ^24 in all packages
- api: bcrypt ^5.1.1 → ^6.0.0 (Node 24 prebuilt binary compat)
- clients/php/ErrorReporter.php: PHP 8.4+ compat audit (no deprecated patterns)
- clients/node/errorReporter.mjs: Node 24+ doc update

All tests verified locally:
- api: 51/51 passed (vitest)
- ingest-api: 40 passed + 14 skipped (vitest)
- collector-worker: 12/12 passed (vitest)
- admin-ui: lint + typecheck clean
- web: lint + typecheck + build clean

Paperclip-Agent: Nelson Baptista (urlKey nelson-baptista; id e34f1b0f-62db-487c-8584-f6a47203f7b5)
Paperclip-Issue: BIT-31723
Paperclip-Run: 76d06689-1879-421f-ad2c-04f5fe85d21d
2026-10-23 17:30:13 +01:00

223 lines
7.1 KiB
PHP

<?php
declare(strict_types=1);
/**
* BitReport Error Reporter — PHP client for errors.bitreport.pt ingest API.
*
* Drop this file into any PHP 8.4+ project. No Composer dependencies.
*
* Usage:
* require_once __DIR__ . '/ErrorReporter.php';
* BitReport\ErrorReporter::registerGlobalHandlers();
*
* Environment variables:
* ERROR_REPORTING_TOKEN — ingest API key (required)
* ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
* ERROR_REPORTING_DISABLED — set to "1" to disable
* ERROR_REPORTING_PROJECT_SLUG — stable product slug for ERRSIG / Paperclip routing (optional)
* ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea, e.g. BitReport.pt/my-product (optional)
*/
namespace BitReport;
final class ErrorReporter
{
private const DEFAULT_ENDPOINT = 'https://errors.bitreport.pt';
private static bool $handlersRegistered = false;
public static function isConfigured(): bool
{
return self::env('ERROR_REPORTING_DISABLED') !== '1'
&& self::env('ERROR_REPORTING_TOKEN') !== '';
}
private static function endpoint(): string
{
$base = self::env('ERROR_REPORTING_ENDPOINT');
if ($base === '') {
$base = self::DEFAULT_ENDPOINT;
}
return rtrim($base, '/') . '/v1/ingest/events';
}
private static function token(): string
{
return self::env('ERROR_REPORTING_TOKEN');
}
private static function projectName(): string
{
return self::env('ERROR_REPORTING_PROJECT_NAME');
}
private static function projectSlug(): string
{
return self::env('ERROR_REPORTING_PROJECT_SLUG');
}
private static function giteaRepo(): string
{
return self::env('ERROR_REPORTING_GITEA_REPO');
}
private static function env(string $key): string
{
$v = getenv($key);
return ($v !== false && $v !== '') ? trim((string) $v) : '';
}
/**
* Register global handlers for fatal errors and uncaught exceptions.
*/
public static function registerGlobalHandlers(): void
{
if (self::$handlersRegistered || !self::isConfigured()) {
return;
}
self::$handlersRegistered = true;
register_shutdown_function(static function (): void {
$err = error_get_last();
if ($err === null || !is_array($err)) {
return;
}
$fatal = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
if (!in_array($err['type'], $fatal, true)) {
return;
}
$file = (string) ($err['file'] ?? '');
$line = (int) ($err['line'] ?? 0);
$syn = $file !== '' && $line > 0
? "[fatal shutdown] {$file}:{$line}"
: '[fatal shutdown] (location unknown)';
self::reportMessage(
(string) $err['message'],
'critical',
$file,
$line,
$syn,
['shutdown' => true, 'errno' => $err['type']]
);
});
set_exception_handler(static function (\Throwable $e): void {
self::reportThrowable($e, ['uncaught' => true]);
error_log('Uncaught ' . $e::class . ': ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
echo 'Internal Server Error';
exit(1);
});
}
public static function reportThrowable(\Throwable $e, array $context = []): void
{
$severity = ($e instanceof \Error) ? 'critical' : 'error';
self::reportMessage(
$e->getMessage(),
$severity,
$e->getFile(),
$e->getLine(),
$e->getTraceAsString(),
array_merge(['error_type' => $e::class], $context)
);
}
/**
* @param array<string, mixed> $context
*/
public static function reportMessage(
string $message,
string $level = 'error',
string $filePath = '',
int $lineNumber = 0,
string $stackTrace = '',
array $context = []
): void {
if (!self::isConfigured()) {
return;
}
$ctx = array_merge([
'file_path' => $filePath,
'line_number' => $lineNumber ?: null,
'php_sapi' => PHP_SAPI,
'request_uri' => $_SERVER['REQUEST_URI'] ?? null,
'http_method' => $_SERVER['REQUEST_METHOD'] ?? null,
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
'project_name' => self::projectName() !== '' ? self::projectName() : null,
'project_slug' => self::projectSlug() !== '' ? self::projectSlug() : null,
'gitea_repo' => self::giteaRepo() !== '' ? self::giteaRepo() : null,
], $context);
// Remove null values
$ctx = array_filter($ctx, static fn($v) => $v !== null && $v !== '');
$event = [
'schema_version' => 1,
'occurred_at' => gmdate('Y-m-d\TH:i:s.v\Z'),
'level' => $level,
'message' => $message,
];
if ($stackTrace !== '') {
$event['stacktrace'] = $stackTrace;
}
if (!empty($ctx)) {
$event['context'] = $ctx;
}
$payload = json_encode(['events' => [$event]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($payload === false) {
return;
}
self::post($payload);
}
private static function post(string $json): void
{
$url = self::endpoint();
$token = self::token();
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $token,
];
try {
if (function_exists('curl_init')) {
$ch = curl_init($url);
if ($ch === false) return;
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 4,
CURLOPT_CONNECTTIMEOUT => 2,
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
]);
@curl_exec($ch);
curl_close($ch);
return;
}
$headerStr = implode("\r\n", $headers);
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => $headerStr . "\r\n",
'content' => $json,
'timeout' => 4,
'ignore_errors' => true,
],
]);
@file_get_contents($url, false, $ctx);
} catch (\Throwable $e) {
error_log('BitReport\\ErrorReporter: send failed: ' . $e->getMessage());
}
}
}