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