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

RequestBodyListener   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 36.36%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 3
dl 0
loc 28
ccs 4
cts 11
cp 0.3636
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelController() 0 15 5
A getSubscribedEvents() 0 6 1
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