ProdVndErrorPage   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 6
eloc 15
dl 0
loc 36
rs 10
c 1
b 1
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A getResponseBody() 0 8 2
A toString() 0 8 1
A getHeader() 0 3 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Provide\Error;
6
7
use BEAR\Resource\ResourceObject;
8
use BEAR\Sunday\Extension\Router\RouterMatch;
9
use Override;
10
use Throwable;
11
12
use function assert;
13
use function json_encode;
14
15
use const JSON_PRETTY_PRINT;
16
use const JSON_UNESCAPED_SLASHES;
17
use const PHP_EOL;
18
19
final class ProdVndErrorPage extends ResourceObject
20
{
21
    public function __construct(Throwable $e, RouterMatch $request)
22
    {
23
        unset($request);
24
        $status = new Status($e);
25
        $this->code = $status->code;
26
        $this->headers = $this->getHeader($status->code);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getHeader($status->code) of type array<string,string> is incompatible with the declared type BEAR\Resource\Headers of property $headers.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
27
        $this->body = $this->getResponseBody($e, $status);
28
    }
29
30
    #[Override]
31
    public function toString(): string
32
    {
33
        $jsonEncoded = json_encode($this->body, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
34
        assert($jsonEncoded !== false);
35
        $this->view = $jsonEncoded . PHP_EOL;
36
37
        return $this->view;
38
    }
39
40
    /** @return array<string, string> */
41
    private function getHeader(int $code): array
42
    {
43
        return ['content-type' => $code >= 500 ? 'application/vnd.error+json' : 'application/json'];
44
    }
45
46
    /** @return array<string, string> */
47
    private function getResponseBody(Throwable $e, Status $status): array
48
    {
49
        $body = ['message' => $status->text];
50
        if ($status->code >= 500) {
51
            $body['logref'] = (string) new LogRef($e);
52
        }
53
54
        return $body;
55
    }
56
}
57