Passed
Pull Request — master (#11)
by Niels
03:50
created

getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the OpenapiBundle package.
5
 *
6
 * (c) Niels Nijens <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Nijens\OpenapiBundle\EventListener;
13
14
use Nijens\OpenapiBundle\Exception\HttpExceptionInterface;
15
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
18
use Symfony\Component\HttpKernel\Exception\HttpException;
19
use Symfony\Component\HttpKernel\KernelEvents;
20
use Symfony\Component\Routing\Route;
21
use Symfony\Component\Routing\RouterInterface;
22
23
/**
24
 * Transforms an exception to a JSON response for OpenAPI routes.
25
 */
26
class JsonResponseExceptionSubscriber implements EventSubscriberInterface
27
{
28
    /**
29
     * @var RouterInterface
30
     */
31
    private $router;
32
33
    /**
34
     * The boolean indicating if the kernel is in debug mode.
35
     *
36
     * @var bool
37
     */
38
    private $debugMode;
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public static function getSubscribedEvents(): array
44
    {
45
        return array(
46
            KernelEvents::EXCEPTION => array(
47
                array('onKernelExceptionTransformToJsonResponse', 0),
48
            ),
49
        );
50
    }
51
52
    /**
53
     * Constructs a new JsonResponseExceptionSubscriber instance.
54
     *
55
     * @param RouterInterface $router
56
     * @param bool            $debugMode
57
     */
58
    public function __construct(RouterInterface $router, bool $debugMode)
59
    {
60
        $this->router = $router;
61
        $this->debugMode = $debugMode;
62
    }
63
64
    /**
65
     * Converts the exception to a JSON response.
66
     *
67
     * @param GetResponseForExceptionEvent $event
68
     */
69
    public function onKernelExceptionTransformToJsonResponse(GetResponseForExceptionEvent $event): void
70
    {
71
        $request = $event->getRequest();
72
73
        $route = $this->router->getRouteCollection()->get(
74
            $request->attributes->get('_route')
75
        );
76
77
        if ($route instanceof Route === false || $route->hasOption('openapi_resource') === false) {
78
            return;
79
        }
80
81
        $response = new JsonResponse();
82
83
        $statusCode = JsonResponse::HTTP_INTERNAL_SERVER_ERROR;
84
        $message = 'Unexpected error.';
85
86
        $exception = $event->getException();
87
        if ($exception instanceof HttpException) {
88
            $statusCode = $exception->getStatusCode();
89
        }
90
91
        if ($this->debugMode || $exception instanceof HttpException) {
92
            $message = $exception->getMessage();
93
        }
94
95
        $responseBody = array('message' => $message);
96
        if ($exception instanceof HttpExceptionInterface) {
97
            $responseBody['errors'] = $exception->getErrors();
98
        }
99
100
        $response->setStatusCode($statusCode);
101
        $response->setData($responseBody);
102
103
        $event->setResponse($response);
104
    }
105
}
106