Failed Conditions
Push — master ( 04c6d9...b84ba2 )
by Adrien
15:58
created

FatalErrorHandler::register()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 7
cp 0
rs 10
cc 4
nc 1
nop 0
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix;
6
7
final class FatalErrorHandler
8
{
9
    /**
10
     * Transform some specific PHP fatal errors into HTTP 500 with a JSON response
11
     * containing the error message (only). So that the client might show the error to the end-user.
12
     *
13
     * This must be called exactly **ONE TIME**.
14
     *
15
     * This will only work if HTTP headers were not sent already. So in development,
16
     * where `error_reporting` is most likely enabled, it might not work.
17
     */
18
    public static function register(): void
19
    {
20
        register_shutdown_function(function (): void {
21
            $message = error_get_last()['message'] ?? null;
22
            if (!headers_sent() && $message && str_starts_with($message, 'Maximum execution time of')) {
23
                header('content-type: application/json');
24
                http_response_code(500);
25
26
                echo json_encode(['message' => $message], JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
27
            }
28
        });
29
    }
30
}
31