RequestTransformerSubscriber   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 12
c 2
b 0
f 0
dl 0
loc 37
ccs 14
cts 14
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 3 2
A onKernelRequest() 0 17 4
A getSubscribedEvents() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace jin2chen\ApiBundle\EventSubscriber;
6
7
use JsonException;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpKernel\Event\RequestEvent;
11
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
12
use Symfony\Component\HttpKernel\KernelEvents;
13
14
use function is_array;
15
use function json_decode;
16
17
use const JSON_THROW_ON_ERROR;
18
19
class RequestTransformerSubscriber implements EventSubscriberInterface
20
{
21 2
    public static function getSubscribedEvents(): array
22
    {
23
        return [
24 2
            KernelEvents::REQUEST => ['onKernelRequest', 1023],
25
        ];
26
    }
27
28
    /**
29
     * @Callback
30
     * @see getSubscribedEvents()
31
     * @param RequestEvent $event
32
     */
33 9
    public function onKernelRequest(RequestEvent $event): void
34
    {
35 9
        $request = $event->getRequest();
36
37 9
        if (false === $this->supports($request)) {
38 7
            return;
39
        }
40
41
        try {
42
            /** @var array|scalar $data */
43 2
            $data = json_decode((string) $request->getContent(), true, 512, JSON_THROW_ON_ERROR);
44
45 1
            if (is_array($data)) {
46 1
                $request->request->replace($data);
47
            }
48 1
        } catch (JsonException $exception) {
49 1
            throw new BadRequestHttpException($exception->getMessage());
50
        }
51 1
    }
52
53 9
    private function supports(Request $request): bool
54
    {
55 9
        return 'json' === $request->getContentType() && $request->getContent();
56
    }
57
}
58