ExceptionListener   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 95.83%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 10
lcom 0
cbo 4
dl 0
loc 61
ccs 23
cts 24
cp 0.9583
rs 10
c 1
b 0
f 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 6 1
B transformException() 0 27 5
A map() 0 12 4
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Rest\ServerBundle\EventListener;
5
6
use Innmind\Rest\Server\Exception\{
7
    Exception as ServerExceptionInterface,
8
    ActionNotImplemented,
9
    HttpResourceDenormalizationException,
10
    FilterNotApplicable
11
};
12
use Innmind\Http\Exception\{
13
    Exception as BaseHttpExceptionInterface,
14
    Http\Exception,
15
    Http\MethodNotAllowed,
16
    Http\BadRequest
17
};
18
use Symfony\Component\{
19
    EventDispatcher\EventSubscriberInterface,
20
    HttpKernel\KernelEvents,
21
    HttpKernel\Event\GetResponseForExceptionEvent,
22
    HttpKernel\Exception\HttpException
23
};
24
25
final class ExceptionListener implements EventSubscriberInterface
26
{
27
    /**
28
     * {@inheritdoc}
29
     */
30 38
    public static function getSubscribedEvents()
31
    {
32
        return [
33 38
            KernelEvents::EXCEPTION => [['transformException', 100]],
34
        ];
35
    }
36
37
    /**
38
     * Transform an innmind http exception into a symfony one to generate the
39
     * appropriate http response
40
     *
41
     * @param GetResponseForExceptionEvent $event
42
     *
43
     * @return void
44
     */
45 12
    public function transformException(GetResponseForExceptionEvent $event)
46
    {
47 12
        $exception = $event->getException();
48
49 12
        if ($exception instanceof ServerExceptionInterface) {
50 6
            $exception = $this->map($exception);
51
        }
52
53
        if (
54 12
            $exception instanceof BaseHttpExceptionInterface &&
55 12
            !$exception instanceof Exception
56
        ) {
57 2
            $exception = new BadRequest;
58
        }
59
60 12
        if (!$exception instanceof Exception) {
61 2
            return;
62
        }
63
64 10
        $event->setException(
65 10
            new HttpException(
66 10
                $exception->httpCode(),
67 10
                null,
68 10
                $exception
69
            )
70
        );
71 10
    }
72
73 6
    private function map(ServerExceptionInterface $exception): \Throwable
74
    {
75
        switch (true) {
76 6
            case $exception instanceof ActionNotImplemented:
77 2
                return new MethodNotAllowed;
78 4
            case $exception instanceof HttpResourceDenormalizationException:
79 2
            case $exception instanceof FilterNotApplicable:
80 4
                return new BadRequest;
81
        }
82
83
        return $exception;
84
    }
85
}
86