Completed
Push — master ( 9d729c...78ea8b )
by Valentyn
03:06
created

RequestBodyListener::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace App\EventListener;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
7
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
8
use Symfony\Component\HttpKernel\KernelEvents;
9
10
class RequestBodyListener implements EventSubscriberInterface
11
{
12 40
    public function onKernelController(FilterControllerEvent $event)
13
    {
14 40
        $request = $event->getRequest();
15
16 40
        if ($request->getContentType() !== 'json' || !$request->getContent()) {
17 40
            return;
18
        }
19
20
        $data = json_decode($request->getContent(), true);
21
        if (json_last_error() !== JSON_ERROR_NONE) {
22
            throw new BadRequestHttpException('Invalid json body: '.json_last_error_msg());
23
        }
24
25
        $request->request->replace(is_array($data) ? $data : []);
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public static function getSubscribedEvents()
32
    {
33
        return [
34
            KernelEvents::CONTROLLER => ['onKernelController', 1],
35
        ];
36
    }
37
}
38