Completed
Pull Request — master (#58)
by Ilya
01:50
created

DeserializeListener::onKernelController()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
nc 4
nop 1
dl 0
loc 29
rs 9.7333
c 3
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Common\Bridge\Symfony\Bundle\Listener;
6
7
use Damax\Common\Bridge\Symfony\Bundle\Annotation\Deserialize;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpKernel\Event\ControllerEvent;
10
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
11
use Symfony\Component\HttpKernel\KernelEvents;
12
use Symfony\Component\Serializer\Exception\ExceptionInterface;
13
use Symfony\Component\Serializer\SerializerInterface;
14
15
class DeserializeListener implements EventSubscriberInterface
16
{
17
    private const CONTENT_TYPE = 'json';
18
19
    private $serializer;
20
21
    public function __construct(SerializerInterface $serializer)
22
    {
23
        $this->serializer = $serializer;
24
    }
25
26
    public static function getSubscribedEvents(): array
27
    {
28
        return [
29
            KernelEvents::CONTROLLER => ['onKernelController', -16],
30
        ];
31
    }
32
33
    /**
34
     * @throws UnprocessableEntityHttpException
35
     */
36
    public function onKernelController(ControllerEvent $event)
37
    {
38
        $request = $event->getRequest();
39
40
        if (!$request->attributes->get('_deserialize')) {
41
            return;
42
        }
43
44
        $contentType = $request->getRequestFormat(null) ?? $request->getContentType();
45
        if (self::CONTENT_TYPE !== $contentType) {
46
            return;
47
        }
48
49
        /** @var Deserialize $config */
50
        $config = $request->attributes->get('_deserialize');
51
52
        // Deserialize body into object.
53
        try {
54
            $object = $this->serializer->deserialize(
55
                $request->getContent(),
56
                $config->className(),
57
                self::CONTENT_TYPE,
58
                $config->context()
59
            );
60
        } catch (ExceptionInterface $e) {
61
            throw new UnprocessableEntityHttpException('Invalid json.');
62
        }
63
64
        $request->attributes->set($config->param(), $object);
65
    }
66
}
67