getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 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