Passed
Pull Request — master (#2043)
by Tarmo
09:30
created

BodySubscriber::isJsonRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/EventSubscriber/BodySubscriber.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\EventSubscriber;
10
11
use App\Utils\JSON;
12
use JsonException;
13
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpKernel\Event\RequestEvent;
16
use function in_array;
17
use function is_array;
18
19
/**
20
 * Class BodySubscriber
21
 *
22
 * @package App\EventSubscriber
23
 * @author TLe, Tarmo Leppänen <[email protected]>
24
 */
25
class BodySubscriber implements EventSubscriberInterface
26
{
27
    /**
28
     * {@inheritdoc}
29
     *
30
     * @return array<string, array<int, string|int>>
31
     */
32 1
    public static function getSubscribedEvents(): array
33
    {
34
        return [
35
            RequestEvent::class => [
36 1
                'onKernelRequest',
37
                10,
38
            ],
39
        ];
40
    }
41
42
    /**
43
     * Implementation of BodySubscriber event. Purpose of this is to convert JSON request data to proper request
44
     * parameters.
45
     *
46
     * @throws JsonException
47
     */
48 346
    public function onKernelRequest(RequestEvent $event): void
49
    {
50
        // Get current request
51 346
        $request = $event->getRequest();
52
53
        // If request has some content and is JSON type convert it to request parameters
54 346
        if ($request->getContent() !== '' && $this->isJsonRequest($request)) {
55 33
            $this->transformJsonBody($request);
56
        }
57
    }
58
59
    /**
60
     * Method to determine if current Request is JSON type or not.
61
     */
62 34
    private function isJsonRequest(Request $request): bool
63
    {
64 34
        return in_array($request->getContentType(), [null, 'json', 'txt'], true);
65
    }
66
67
    /**
68
     * Method to transform JSON type request to proper request parameters.
69
     *
70
     * @throws JsonException
71
     */
72 33
    private function transformJsonBody(Request $request): void
73
    {
74 33
        $data = JSON::decode($request->getContent(), true);
75
76 32
        if (is_array($data)) {
77 32
            $request->request->replace($data);
78
        }
79
    }
80
}
81