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
|
|
|
|