|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Subscriber; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
6
|
|
|
|
|
7
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
|
8
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; |
|
9
|
|
|
use Symfony\Component\HttpKernel\Event\KernelEvent; |
|
10
|
|
|
|
|
11
|
|
|
use Symfony\Component\Translation\TranslatorInterface; |
|
12
|
|
|
|
|
13
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
|
17
|
|
|
|
|
18
|
|
|
class JsonRequestSubscriber implements EventSubscriberInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** @var TranslatorInterface **/ |
|
21
|
|
|
protected $translator; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param TranslatorInterface $translator |
|
25
|
|
|
*/ |
|
26
|
15 |
|
public function __construct(TranslatorInterface $translator) |
|
27
|
|
|
{ |
|
28
|
15 |
|
$this->translator = $translator; |
|
29
|
15 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @return array |
|
33
|
|
|
*/ |
|
34
|
1 |
|
public static function getSubscribedEvents() |
|
35
|
|
|
{ |
|
36
|
|
|
return [ |
|
37
|
1 |
|
'kernel.request' => 'onKernelRequest', |
|
38
|
|
|
'kernel.exception' => 'onKernelException' |
|
39
|
|
|
]; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
15 |
|
public function onKernelRequest(GetResponseEvent $event) |
|
43
|
|
|
{ |
|
44
|
15 |
|
$request = $event->getRequest(); |
|
45
|
15 |
|
if (!$this->isJsonRequest($event) || empty($request->getContent())) { |
|
46
|
11 |
|
return; |
|
47
|
|
|
} |
|
48
|
4 |
|
$request->request->add(json_decode($request->getContent(), true)); |
|
49
|
4 |
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function onKernelException(GetResponseForExceptionEvent $event) |
|
52
|
|
|
{ |
|
53
|
|
|
if (!$this->isJsonRequest($event)) { |
|
54
|
|
|
return; |
|
55
|
|
|
} |
|
56
|
|
|
$exception = $event->getException(); |
|
57
|
|
|
$event->setResponse(new JsonResponse([ |
|
58
|
|
|
'message' => $this->translator->trans($exception->getMessage()) |
|
59
|
|
|
], ($exception instanceof HttpException) ? $exception->getStatusCode(): 500)); |
|
60
|
|
|
$event->stopPropagation(); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
15 |
|
protected function isJsonRequest(KernelEvent $event): bool |
|
64
|
|
|
{ |
|
65
|
15 |
|
return ($event->getRequest()->getContentType() === 'json'); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|