Passed
Push — master ( 9fe00e...ce2820 )
by Koldo
10:56
created

ServerRequestErrorResponseGenerator::__construct()   A

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 0
Metric Value
cc 1
eloc 1
c 0
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 Antidot\Application\Http\Response;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Throwable;
10
use Zend\Diactoros\Response;
11
12
final class ServerRequestErrorResponseGenerator implements ErrorResponseGenerator
13
{
14
    public const ERROR_MESSAGE = 'An unexpected error occurred';
15
    public const ERROR_CODE = 500;
16
    /** @var bool * */
17
    private $devMode;
18
19 1
    public function __construct(bool $devMode = false)
20
    {
21 1
        $this->devMode = $devMode;
22 1
    }
23
24 1
    public function __invoke(
25
        Throwable $e,
26
        ServerRequestInterface $request = null,
27
        ResponseInterface $response = null
28
    ): ResponseInterface {
29 1
        if (null === $response) {
30 1
            $response = new Response();
31
        }
32 1
        $response = $response->withStatus(self::ERROR_CODE);
33
34 1
        if ($this->devMode) {
35
            $response = $response->withHeader('Content-Type', 'application/json');
36
            $response->getBody()->write($this->getErrorAsJsonString($e, $request));
37
38
            return $response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response could return the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface. Consider adding an additional type-check to rule them out.
Loading history...
39
        }
40
41 1
        $response->getBody()->write(self::ERROR_MESSAGE);
42
43 1
        return $response;
44
    }
45
46
    private function getErrorAsJsonString(Throwable $e, ServerRequestInterface $request = null): string
47
    {
48
        $responseString = json_encode([
49
            'exception' => [
50
                'class' => get_class($e),
51
                'message' => $e->getMessage(),
52
                'code' => $e->getCode(),
53
                'file' => $e->getFile(),
54
                'line' => $e->getLine(),
55
56
                'previous' => null === $e->getPrevious() ?: get_class($e->getPrevious()),
57
                'trace' => $e->getTrace(),
58
            ],
59
            'request' => null === $request ?: [
60
                'headers' => $request->getHeaders(),
61
            ]
62
        ]);
63
64
        return is_string($responseString) ? $responseString : $e->getMessage();
0 ignored issues
show
introduced by
The condition is_string($responseString) is always true.
Loading history...
65
    }
66
}
67