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

FatalErrorHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 7
c 1
b 0
f 0
dl 0
loc 20
ccs 0
cts 7
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A register() 0 9 4
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