ErrorResponseGenerator   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 57
ccs 14
cts 14
cp 1
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A generate() 0 12 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace HttpSoft\Basis\ErrorHandler;
6
7
use HttpSoft\Basis\Response\ExtractErrorDataTrait;
8
use HttpSoft\Basis\TemplateRendererInterface;
9
use HttpSoft\ErrorHandler\ErrorResponseGeneratorInterface;
10
use Psr\Http\Message\ResponseFactoryInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Throwable;
14
15
final class ErrorResponseGenerator implements ErrorResponseGeneratorInterface
16
{
17
    use ExtractErrorDataTrait;
18
19
    /**
20
     * @var ResponseFactoryInterface
21
     */
22
    private ResponseFactoryInterface $responseFactory;
23
24
    /**
25
     * @var TemplateRendererInterface
26
     */
27
    private TemplateRendererInterface $template;
28
29
    /**
30
     * @var string
31
     */
32
    private string $view;
33
34
    /**
35
     * @var bool
36
     */
37
    private bool $debug;
38
39
    /**
40
     * @param ResponseFactoryInterface $responseFactory
41
     * @param TemplateRendererInterface $template
42
     * @param string $view
43
     * @param bool $debug
44
     */
45 14
    public function __construct(
46
        ResponseFactoryInterface $responseFactory,
47
        TemplateRendererInterface $template,
48
        string $view,
49
        bool $debug = false
50
    ) {
51 14
        $this->responseFactory = $responseFactory;
52 14
        $this->template = $template;
53 14
        $this->view = $view;
54 14
        $this->debug = $debug;
55
    }
56
57
    /**
58
     * {@inheritDoc}
59
     */
60 6
    public function generate(Throwable $error, ServerRequestInterface $request): ResponseInterface
61
    {
62 6
        $response = $this->responseFactory->createResponse($this->extractErrorStatusCode($error));
63
64 6
        $response->getBody()->write($this->template->render($this->view, [
65 6
            'response' => $response,
66 6
            'request' => $request,
67 6
            'exception' => $error,
68 6
            'debug' => $this->debug,
69 6
        ]));
70
71 6
        return $response;
72
    }
73
}
74