-
-
Notifications
You must be signed in to change notification settings - Fork 963
Expand file tree
/
Copy pathDeserializeProvider.php
More file actions
152 lines (124 loc) · 6.38 KB
/
DeserializeProvider.php
File metadata and controls
152 lines (124 loc) · 6.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\State\Provider;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\SerializerContextBuilderInterface;
use ApiPlatform\State\StopwatchAwareInterface;
use ApiPlatform\State\StopwatchAwareTrait;
use ApiPlatform\Validator\Exception\ValidationException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorTrait;
final class DeserializeProvider implements ProviderInterface, StopwatchAwareInterface
{
use StopwatchAwareTrait;
public function __construct(
private readonly ?ProviderInterface $decorated,
private readonly SerializerInterface $serializer,
private readonly SerializerContextBuilderInterface $serializerContextBuilder,
private ?TranslatorInterface $translator = null,
) {
if (null === $this->translator) {
$this->translator = new class implements TranslatorInterface, LocaleAwareInterface {
use TranslatorTrait;
};
$this->translator->setLocale('en');
}
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
// We need request content
if (!$operation instanceof HttpOperation || !($request = $context['request'] ?? null)) {
return $this->decorated?->provide($operation, $uriVariables, $context);
}
$data = $this->decorated ? $this->decorated->provide($operation, $uriVariables, $context) : $request->attributes->get('data');
if (!$operation->canDeserialize() || $context['request']->attributes->has('deserialized')) {
return $data;
}
$this->stopwatch?->start('api_platform.provider.deserialize');
$contentType = $request->headers->get('CONTENT_TYPE');
if (null === $contentType || '' === $contentType) {
throw new UnsupportedMediaTypeHttpException('The "Content-Type" header must exist.');
}
$serializerContext = $this->serializerContextBuilder->createFromRequest($request, false, [
'resource_class' => $operation->getClass(),
'operation' => $operation,
]);
$serializerContext['uri_variables'] = $uriVariables;
if (!$format = $request->attributes->get('input_format') ?? null) {
throw new UnsupportedMediaTypeHttpException('Format not supported.');
}
if (null === ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? null)) {
$method = $operation->getMethod();
$assignObjectToPopulate = 'POST' === $method
|| 'PATCH' === $method
|| ('PUT' === $method && !($operation->getExtraProperties()['standard_put'] ?? true));
if ($assignObjectToPopulate) {
$serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] = true;
trigger_deprecation('api-platform/core', '5.0', 'To assign an object to populate you should set "%s" in your denormalizationContext, not defining it is deprecated.', SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE);
}
}
if (null !== $data && ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? false)) {
$serializerContext[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
}
unset($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE]);
try {
$class = $operation->getInput()['class'] ?? $operation->getClass();
$data = $this->serializer->deserialize((string) $request->getContent(), $serializerContext['deserializer_type'] ?? $class, $format, $serializerContext);
} catch (PartialDenormalizationException $e) {
if (!class_exists(ConstraintViolationList::class)) {
throw $e;
}
$violations = new ConstraintViolationList();
foreach ($e->getErrors() as $exception) {
if (!$exception instanceof NotNormalizableValueException) {
continue;
}
$expectedTypes = $this->normalizeExpectedTypes($exception->getExpectedTypes());
$message = (new Type($expectedTypes))->message;
$parameters = [];
if ($exception->canUseMessageForUser()) {
$parameters['hint'] = $exception->getMessage();
}
$violations->add(new ConstraintViolation($this->translator->trans($message, ['{{ type }}' => implode('|', $expectedTypes)], 'validators'), $message, $parameters, null, $exception->getPath(), null, null, (string) Type::INVALID_TYPE_ERROR));
}
if (0 !== \count($violations)) {
throw new ValidationException($violations);
}
}
$this->stopwatch?->stop('api_platform.provider.deserialize');
$request->attributes->set('data', $data);
return $data;
}
private function normalizeExpectedTypes(?array $expectedTypes = null): array
{
$normalizedTypes = [];
foreach ($expectedTypes ?? [] as $expectedType) {
$normalizedType = $expectedType;
if (class_exists($expectedType) || interface_exists($expectedType)) {
$classReflection = new \ReflectionClass($expectedType);
$normalizedType = $classReflection->getShortName();
}
$normalizedTypes[] = $normalizedType;
}
return $normalizedTypes;
}
}