1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the OpenapiBundle package. |
7
|
|
|
* |
8
|
|
|
* (c) Niels Nijens <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Nijens\OpenapiBundle\Deserialization\EventSubscriber; |
15
|
|
|
|
16
|
|
|
use Nijens\OpenapiBundle\Deserialization\DeserializationContext; |
17
|
|
|
use Nijens\OpenapiBundle\Routing\RouteContext; |
18
|
|
|
use Nijens\OpenapiBundle\Validation\ValidationContext; |
19
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
20
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
21
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
22
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
23
|
|
|
|
24
|
|
|
class JsonRequestBodyDeserializationSubscriber implements EventSubscriberInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var SerializerInterface |
28
|
|
|
*/ |
29
|
|
|
private $serializer; |
30
|
|
|
|
31
|
|
|
public static function getSubscribedEvents(): array |
32
|
|
|
{ |
33
|
|
|
return [ |
34
|
|
|
KernelEvents::REQUEST => [ |
35
|
|
|
['deserializeRequestBody', 27], |
36
|
|
|
], |
37
|
|
|
]; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function __construct(SerializerInterface $serializer) |
41
|
|
|
{ |
42
|
|
|
$this->serializer = $serializer; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function deserializeRequestBody(RequestEvent $event): void |
46
|
|
|
{ |
47
|
|
|
$request = $event->getRequest(); |
48
|
|
|
|
49
|
|
|
// TODO Add defaults from OpenAPI schema. |
50
|
|
|
|
51
|
|
|
$routeContext = $request->attributes->get(RouteContext::REQUEST_ATTRIBUTE); |
52
|
|
|
$validationContext = $request->attributes->get(ValidationContext::REQUEST_ATTRIBUTE); |
53
|
|
|
|
54
|
|
|
if ($validationContext === null || isset($routeContext[RouteContext::DESERIALIZATION_OBJECT]) === false) { |
55
|
|
|
return; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$request->attributes->set( |
59
|
|
|
DeserializationContext::REQUEST_ATTRIBUTE, |
60
|
|
|
$this->serializer->deserialize( |
61
|
|
|
$validationContext[ValidationContext::REQUEST_BODY], |
62
|
|
|
$routeContext[RouteContext::DESERIALIZATION_OBJECT], |
63
|
|
|
$request->getContentType() |
|
|
|
|
64
|
|
|
) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|