|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the FOSRestBundle package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace FOS\RestBundle\EventListener; |
|
13
|
|
|
|
|
14
|
|
|
use FOS\RestBundle\FOSRestBundle; |
|
15
|
|
|
use FOS\RestBundle\Util\ExceptionValueMap; |
|
16
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
17
|
|
|
use Symfony\Component\HttpKernel\Event\ExceptionEvent; |
|
18
|
|
|
use Symfony\Component\HttpKernel\Event\ResponseEvent; |
|
19
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @author Christian Flothmann <[email protected]> |
|
23
|
|
|
*/ |
|
24
|
|
|
class ResponseStatusCodeListener implements EventSubscriberInterface |
|
25
|
|
|
{ |
|
26
|
|
|
private $exceptionValueMap; |
|
27
|
|
|
private $responseStatusCode; |
|
28
|
|
|
|
|
29
|
5 |
|
public function __construct(ExceptionValueMap $exceptionValueMap) |
|
30
|
|
|
{ |
|
31
|
5 |
|
$this->exceptionValueMap = $exceptionValueMap; |
|
32
|
5 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
public static function getSubscribedEvents(): array |
|
35
|
|
|
{ |
|
36
|
|
|
return [ |
|
37
|
|
|
KernelEvents::EXCEPTION => 'getResponseStatusCodeFromThrowable', |
|
38
|
|
|
KernelEvents::RESPONSE => 'setResponseStatusCode', |
|
39
|
|
|
]; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
5 |
|
public function getResponseStatusCodeFromThrowable(ExceptionEvent $event): void |
|
43
|
|
|
{ |
|
44
|
5 |
|
if (!$event->isMasterRequest()) { |
|
45
|
1 |
|
return; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
5 |
|
$request = $event->getRequest(); |
|
49
|
|
|
|
|
50
|
5 |
|
if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) { |
|
51
|
1 |
|
return; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
4 |
|
$statusCode = $this->exceptionValueMap->resolveFromClassName(get_class($event->getThrowable())); |
|
55
|
|
|
|
|
56
|
4 |
|
if (is_int($statusCode)) { |
|
57
|
3 |
|
$this->responseStatusCode = $statusCode; |
|
58
|
|
|
} |
|
59
|
4 |
|
} |
|
60
|
|
|
|
|
61
|
5 |
|
public function setResponseStatusCode(ResponseEvent $event): void |
|
62
|
|
|
{ |
|
63
|
5 |
|
if (!$event->isMasterRequest()) { |
|
64
|
1 |
|
return; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
5 |
|
if (null !== $this->responseStatusCode) { |
|
68
|
3 |
|
$event->getResponse()->setStatusCode($this->responseStatusCode); |
|
69
|
|
|
|
|
70
|
3 |
|
$this->responseStatusCode = null; |
|
71
|
|
|
} |
|
72
|
5 |
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|