ApiProblemExceptionHandler::__invoke()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 9.52
c 0
b 0
f 0
cc 3
nc 3
nop 3
1
<?php
2
3
namespace Scheduler\Web\Radar\Middleware;
4
5
use Exception;
6
use Crell\ApiProblem\ApiProblem;
7
use Psr\Http\Message\ServerRequestInterface as Request;
8
use Psr\Http\Message\ResponseInterface as Response;
9
10
class ApiProblemExceptionHandler extends \Relay\Middleware\ExceptionHandler
11
{
12
    const SERVER_ERROR_MESSAGE = "We're experiencing some trouble.";
13
14
    public function __invoke(Request $request, Response $response, callable $next)
15
    {
16
        try {
17
            $response = $next($request, $response);
18
        } catch (Exception $e) {
19
            $response = $this->exceptionResponse
20
                                ->withStatus(500)
21
                                ->withHeader('Content-Type', 'application/problem+json');
22
23
            $problem = new ApiProblem();
24
            $problem->setTitle($response->getReasonPhrase());
25
            $problem->setStatus(500);
26
            $problem->setInstance((string) $request->getUri());
27
28
            if (getenv("APP_ENV") == "dev") {
29
                $problem->setDetail($e->getMessage());
30
            } else {
31
                $problem->setDetail(self::SERVER_ERROR_MESSAGE);
32
            }
33
34
            $response->getBody()->write($problem->asJson());
35
        }
36
37
        return $response;
38
    }
39
}
40