RequestBodySubscriber   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 9
c 1
b 0
f 0
dl 0
loc 21
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelRequest() 0 13 5
A getSubscribedEvents() 0 4 1
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