-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathItemNormalizerTrait.php
More file actions
160 lines (137 loc) · 7.24 KB
/
Copy pathItemNormalizerTrait.php
File metadata and controls
160 lines (137 loc) · 7.24 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
153
154
155
156
157
158
159
160
<?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\JsonApi\Serializer;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Serializer\AbstractItemNormalizer;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Exception\RuntimeException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* Shared support gates and denormalization logic for the JSON:API item (de)normalizer.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*
* @internal
*/
trait ItemNormalizerTrait
{
public function getSupportedTypes(?string $format): array
{
return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
}
public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
{
return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
}
/**
* @throws NotNormalizableValueException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
// When re-entering for input DTO denormalization, data has already been
// unwrapped from the JSON:API structure by the first pass. Skip extraction.
if (isset($context['api_platform_input'])) {
return parent::denormalize($data, $type, $format, $context);
}
$operation = $context['operation'] ?? null;
$isPostOperation = $operation instanceof HttpOperation && 'POST' === $operation->getMethod();
$allowClientGeneratedId = true === ($context[ItemNormalizer::ALLOW_CLIENT_GENERATED_ID] ?? $this->defaultContext[ItemNormalizer::ALLOW_CLIENT_GENERATED_ID] ?? false);
// Avoid issues with proxies if we populated the object
if (!isset($context[AbstractItemNormalizer::OBJECT_TO_POPULATE]) && isset($data['data']['id'])) {
if ($isPostOperation) {
if (!$allowClientGeneratedId) {
throw new NotNormalizableValueException(\sprintf('Client-generated IDs are not allowed on this operation. Set the "%s" denormalization context flag (or the bundle "allow_client_generated_id" configuration) to enable it.', ItemNormalizer::ALLOW_CLIENT_GENERATED_ID));
}
// Fall through: client id is merged into the denormalized payload below.
} elseif (true !== ($context['api_allow_update'] ?? true)) {
throw new NotNormalizableValueException('Update is not allowed for this operation.');
} else {
$context += ['fetch_data' => false];
if ($this->useIriAsId) {
$context[AbstractItemNormalizer::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($data['data']['id'], $context);
} elseif ($operation instanceof HttpOperation) {
$iri = $this->reconstructIri($type, (string) $data['data']['id'], $operation);
$context[AbstractItemNormalizer::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($iri, $context);
}
}
}
$dataToDenormalize = array_merge(
$data['data']['attributes'] ?? [],
$data['data']['relationships'] ?? []
);
// Surface the client-generated id so the entity setter receives it.
if ($isPostOperation && $allowClientGeneratedId && isset($data['data']['id'])) {
$dataToDenormalize['id'] = $data['data']['id'];
}
return parent::denormalize($dataToDenormalize, $type, $format, $context);
}
protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
{
return preg_match('/^\\w[-\\w_]*$/', $attribute) && parent::isAllowedAttribute($classOrObject, $attribute, $format, $context);
}
protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
{
parent::setAttributeValue($object, $attribute, \is_array($value) && \array_key_exists('data', $value) ? $value['data'] : $value, $format, $context);
}
/**
* @see http://jsonapi.org/format/#document-resource-object-linkage
*
* @throws RuntimeException
* @throws UnexpectedValueException
*/
protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
{
if (!\is_array($value) || !isset($value['id'], $value['type'])) {
throw new UnexpectedValueException('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.');
}
try {
$context += ['fetch_data' => true];
if ($this->useIriAsId) {
return $this->iriConverter->getResourceFromIri($value['id'], $context);
}
/** @var HttpOperation $getOperation */
$getOperation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(httpOperation: true);
$iri = $this->reconstructIri($className, (string) $value['id'], $getOperation);
return $this->iriConverter->getResourceFromIri($iri, $context);
} catch (ItemNotFoundException $e) {
if (!isset($context['not_normalizable_value_exceptions'])) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
$context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
$e->getMessage(),
$value,
[$className],
$context['deserialization_path'] ?? null,
true,
$e->getCode(),
$e
);
return null;
}
}
/**
* Maps the id to the operation's single URI variable parameter and generates the IRI.
* Composite identifiers on a single Link work naturally since the composite string
* (e.g. "field1=val1;field2=val2") is passed as-is.
*/
private function reconstructIri(string $resourceClass, string $id, HttpOperation $operation): string
{
$uriVariables = $operation->getUriVariables() ?? [];
if (\count($uriVariables) > 1) {
throw new UnexpectedValueException(\sprintf('JSON:API entity identifier mode requires operations with a single URI variable, operation "%s" has %d. Consider adding a NotExposed Get operation on the resource.', $operation->getName() ?? $operation->getUriTemplate(), \count($uriVariables)));
}
$parameterName = array_key_first($uriVariables) ?? 'id';
return $this->iriConverter->getIriFromResource($resourceClass, UrlGeneratorInterface::ABS_PATH, $operation, ['uri_variables' => [$parameterName => $id]]);
}
}