Completed
Push — develop ( 99c8cd...370699 )
by Baptiste
02:34
created

ExceptionListener::map()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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