RequestBodySubscriber::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace App\EventSubscriber;
4
5
use function json_decode;
6
use function json_last_error;
7
use function json_last_error_msg;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
11
12
class RequestBodySubscriber implements EventSubscriberInterface
13
{
14
    public function onKernelRequest(GetResponseEvent $event): void
15
    {
16
        $request = $event->getRequest();
17
        if ('json' !== $request->getContentType() || !$request->getContent()) {
18
            return;
19
        }
20
21
        $data = json_decode((string) $request->getContent(), true);
22
        if (JSON_ERROR_NONE !== json_last_error()) {
23
            throw new BadRequestHttpException('invalid json body: '.json_last_error_msg());
24
        }
25
26
        $request->request->replace(is_array($data) ? $data : []);
27
    }
28
29
    public static function getSubscribedEvents(): array
30
    {
31
        return [
32
            'kernel.request' => 'onKernelRequest',
33
        ];
34
    }
35
}
36