Passed
Push — master ( a85640...f71496 )
by Jin
02:34
created

RequestTransformerSubscriber::onKernelRequest()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.9666
cc 4
nc 6
nop 1
crap 4
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\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpKernel\Event\RequestEvent;
13
use Symfony\Component\HttpKernel\KernelEvents;
14
15
use function is_array;
16
use function json_decode;
17
18
use const JSON_THROW_ON_ERROR;
19
20
class RequestTransformerSubscriber implements EventSubscriberInterface
21
{
22 2
    public static function getSubscribedEvents(): array
23
    {
24
        return [
25 2
            KernelEvents::REQUEST => ['onKernelRequest', 1023],
26
        ];
27
    }
28
29
    /**
30
     * @Callback
31
     * @see getSubscribedEvents()
32
     * @param RequestEvent $event
33
     */
34 9
    public function onKernelRequest(RequestEvent $event): void
35
    {
36 9
        $request = $event->getRequest();
37
38 9
        if (false === $this->supports($request)) {
39 7
            return;
40
        }
41
42
        try {
43
            /** @var array|scalar $data */
44 2
            $data = json_decode((string) $request->getContent(), true, 512, JSON_THROW_ON_ERROR);
45
46 1
            if (is_array($data)) {
47 1
                $request->request->replace($data);
48
            }
49 1
        } catch (JsonException $exception) {
50 1
            $event->setResponse(new JsonResponse(['message' => $exception->getMessage()], Response::HTTP_BAD_REQUEST));
51
        }
52 2
    }
53
54 9
    private function supports(Request $request): bool
55
    {
56 9
        return 'json' === $request->getContentType() && $request->getContent();
57
    }
58
}
59