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

RequestBodyListener::onKernelController()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 9.2876

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 4
cts 9
cp 0.4444
rs 8.8571
cc 5
eloc 8
nc 3
nop 1
crap 9.2876
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
}