Completed
Push — master ( e9aa8d...83c2fa )
by Artem
05:16
created

JsonDecoderListener::__invoke()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.8977
c 0
b 0
f 0
cc 6
nc 8
nop 1
1
<?php
2
/*
3
 * This file is part of the StfalconApiBundle.
4
 *
5
 * (c) Stfalcon LLC <stfalcon.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace StfalconStudio\ApiBundle\EventListener\Kernel;
14
15
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
16
use Symfony\Component\HttpFoundation\ParameterBag;
17
use Symfony\Component\HttpKernel\Event\RequestEvent;
18
19
/**
20
 * JsonDecoderListener.
21
 */
22
final class JsonDecoderListener implements EventSubscriberInterface
23
{
24
    public const HEADER_CONTENT_TYPE = 'Content-Type';
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public static function getSubscribedEvents(): \Generator
30
    {
31
        yield RequestEvent::class => '__invoke';
32
    }
33
34
    /**
35
     * @param RequestEvent $event
36
     */
37
    public function __invoke(RequestEvent $event): void
38
    {
39
        if (!$event->isMasterRequest()) {
40
            return;
41
        }
42
43
        $request = $event->getRequest();
44
45
        if ($request->headers->has(self::HEADER_CONTENT_TYPE)) {
46
            $contentType = $request->headers->all(self::HEADER_CONTENT_TYPE);
47
48
            if (\is_array($contentType)) {
49
                $contentType = \implode(',', $contentType);
50
            }
51
            $contentType = (string) $contentType;
52
53
            if (\mb_substr_count($contentType, 'application/json') > 0) {
54
                $data = \json_decode((string) $request->getContent(), true);
55
56
                if (\is_array($data)) {
57
                    $request->request = new ParameterBag($data);
58
                }
59
            }
60
        }
61
    }
62
}
63