Completed
Push — master ( 338899...97cb5e )
by Valentyn
03:07
created

RequestBodyListener::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 2
cp 0
rs 9.4285
cc 1
eloc 3
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 36
    public function onKernelController(FilterControllerEvent $event)
13
    {
14 36
        $request = $event->getRequest();
15
16 36
        if ($request->getContentType() != 'json' || !$request->getContent()) {
17 36
            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
     * {@inheritdoc}
29
     */
30
    public static function getSubscribedEvents()
31
    {
32
        return [
33
            KernelEvents::CONTROLLER => ['onKernelController', 1],
34
        ];
35
    }
36
}