ErrorJsonResponseGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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\Response\PrepareJsonDataTrait;
9
use HttpSoft\ErrorHandler\ErrorResponseGeneratorInterface;
10
use HttpSoft\Response\JsonResponse;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Throwable;
14
15
final class ErrorJsonResponseGenerator implements ErrorResponseGeneratorInterface
16
{
17
    use ExtractErrorDataTrait;
18
    use PrepareJsonDataTrait;
19
20
    /**
21
     * @var bool
22
     */
23
    private bool $debug;
24
25
    /**
26
     * @param bool $debug
27
     */
28 18
    public function __construct(bool $debug = false)
29
    {
30 18
        $this->debug = $debug;
31
    }
32
33
    /**
34
     * {@inheritDoc}
35
     */
36 6
    public function generate(Throwable $error, ServerRequestInterface $request): ResponseInterface
37
    {
38 6
        $code = $this->extractErrorStatusCode($error);
39 6
        $message = ErrorResponseGeneratorInterface::ERROR_PHRASES[$code];
40 6
        $data = ['name' => 'Error', 'code' => $code, 'message' => $message];
41
42 6
        if ($this->debug) {
43 3
            $data['exception'] = $this->extractExceptionData($error);
44 3
            $data['request'] = $this->extractRequestData($request);
45
        }
46
47 6
        return new JsonResponse($this->prepareJsonData($data), $code);
48
    }
49
}
50