VndError   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 12
Bugs 1 Features 2
Metric Value
eloc 19
c 12
b 1
f 2
dl 0
loc 52
ccs 21
cts 21
cp 1
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A transfer() 0 4 1
A isCodeExists() 0 7 4
A handle() 0 15 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Sunday\Provide\Error;
6
7
use BEAR\Resource\Code;
8
use BEAR\Resource\Exception\BadRequestException as BadRequest;
9
use BEAR\Resource\Exception\ResourceNotFoundException as NotFound;
10
use BEAR\Resource\Exception\ServerErrorException as ServerError;
11
use BEAR\Sunday\Extension\Error\ErrorInterface;
12
use BEAR\Sunday\Extension\Router\RouterMatch as Request;
13
use BEAR\Sunday\Extension\Transfer\TransferInterface;
14
use Exception;
15
16
use function array_key_exists;
17
use function error_log;
18
19
/**
20
 * Vnd.Error media type error
21
 *
22
 * @see https://github.com/blongden/vnd.error
23
 */
24
final class VndError implements ErrorInterface
25
{
26
    private const CONTENT_TYPE = 'application/vnd.error+json';
27
28
    /** @var array{Content-Type: string} */
29
    public $headers = ['Content-Type' => ''];
30
31
    /** @var array{message: string} */
32
    public $body = ['message' => ''];
33
    private ErrorPage $errorPage;
34
35
    public function __construct(
36
        private TransferInterface $transfer,
37 6
    ) {
38
        $this->errorPage = new ErrorPage();
39 6
    }
40 6
41 6
    /**
42
     * {@inheritDoc}
43
     *
44
     * @noinspection ForgottenDebugOutputInspection
45
     */
46 5
    public function handle(Exception $e, Request $request) // phpcs:disable SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly.ReferencedGeneralException
47
    {
48 5
        if ($this->isCodeExists($e)) {
49 3
            $this->errorPage->code = (int) $e->getCode();
50 3
            $this->errorPage->body = ['message' => (new Code())->statusText[$this->errorPage->code]];
51
52 3
            return $this;
53
        }
54 2
55 2
        $this->errorPage->code = 500;
56 2
        $this->errorPage->body = ['message' => '500 Server Error'];
57 2
        error_log((string) $request);
58
        error_log((string) $e);
59 2
60
        return $this;
61
    }
62
63
    public function transfer(): void
64
    {
65 5
        $this->errorPage->headers['Content-Type'] = self::CONTENT_TYPE;
66
        $this->transfer->__invoke($this->errorPage, []);
67 5
    }
68 5
69 5
    private function isCodeExists(Exception $e): bool
70
    {
71 5
        if (! ($e instanceof NotFound) && ! ($e instanceof BadRequest) && ! ($e instanceof ServerError)) {
72
            return false;
73 5
        }
74 1
75
        return array_key_exists($e->getCode(), (new Code())->statusText);
76
    }
77
}
78