Completed
Push — main ( bdd72f...bbe282 )
by Niels
15s queued 12s
created

onKernelExceptionCreateJsonResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 15
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the OpenapiBundle package.
7
 *
8
 * (c) Niels Nijens <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Nijens\OpenapiBundle\ExceptionHandling\EventSubscriber;
15
16
use Nijens\OpenapiBundle\ExceptionHandling\Exception\ProblemExceptionInterface;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
20
use Symfony\Component\HttpKernel\KernelEvents;
21
use Symfony\Component\Serializer\SerializerInterface;
22
23
/**
24
 * Creates a JSON response from an exception implementing the {@see ProblemExceptionInterface}.
25
 *
26
 * @author Niels Nijens <[email protected]>
27
 */
28
final class ProblemExceptionToJsonResponseSubscriber implements EventSubscriberInterface
29
{
30
    /**
31
     * @var SerializerInterface
32
     */
33
    private $serializer;
34
35
    public static function getSubscribedEvents(): array
36
    {
37
        return [
38
            KernelEvents::EXCEPTION => [
39
                ['onKernelExceptionCreateJsonResponse', 0],
40
            ],
41
        ];
42
    }
43
44
    public function __construct(SerializerInterface $serializer)
45
    {
46
        $this->serializer = $serializer;
47
    }
48
49
    public function onKernelExceptionCreateJsonResponse(ExceptionEvent $event): void
50
    {
51
        $throwable = $event->getThrowable();
52
        if ($throwable instanceof ProblemExceptionInterface === false) {
53
            return;
54
        }
55
56
        $response = JsonResponse::fromJsonString(
57
            $this->serializer->serialize($throwable, 'json'),
58
            $throwable->getStatusCode(),
59
            $throwable->getHeaders()
60
        );
61
        $response->headers->set('Content-Type', 'application/problem+json');
62
63
        $event->setResponse($response);
64
    }
65
}
66