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', 6], |
||
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 | $routeContext = $request->attributes->get(RouteContext::REQUEST_ATTRIBUTE); |
||
50 | $validationContext = $request->attributes->get(ValidationContext::REQUEST_ATTRIBUTE); |
||
51 | |||
52 | if ($validationContext === null || isset($routeContext[RouteContext::DESERIALIZATION_OBJECT]) === false) { |
||
53 | return; |
||
54 | } |
||
55 | |||
56 | /** |
||
57 | * TODO: Remove when support for Symfony 6.4 is dropped. |
||
58 | */ |
||
59 | $format = method_exists($request, 'getContentTypeFormat') ? $request->getContentTypeFormat() : $request->getContentType(); |
||
60 | |||
61 | $request->attributes->set( |
||
62 | DeserializationContext::REQUEST_ATTRIBUTE, |
||
63 | $this->serializer->deserialize( |
||
64 | $validationContext[ValidationContext::REQUEST_BODY], |
||
65 | $routeContext[RouteContext::DESERIALIZATION_OBJECT], |
||
66 | $format |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
67 | ) |
||
68 | ); |
||
69 | } |
||
70 | } |
||
71 |