vendor/api-platform/core/src/Serializer/SerializerContextBuilder.php line 36

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the API Platform project.
  4. *
  5. * (c) Kévin Dunglas <dunglas@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Serializer;
  12. use ApiPlatform\Core\Api\OperationType;
  13. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  14. use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
  15. use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
  16. use ApiPlatform\Exception\RuntimeException;
  17. use ApiPlatform\Metadata\CollectionOperationInterface;
  18. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  19. use ApiPlatform\Util\RequestAttributesExtractor;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\Serializer\Encoder\CsvEncoder;
  22. /**
  23. * {@inheritdoc}
  24. *
  25. * @author Kévin Dunglas <dunglas@gmail.com>
  26. */
  27. final class SerializerContextBuilder implements SerializerContextBuilderInterface
  28. {
  29. private $resourceMetadataFactory;
  30. public function __construct($resourceMetadataFactory)
  31. {
  32. $this->resourceMetadataFactory = $resourceMetadataFactory;
  33. if (!$resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  34. trigger_deprecation('api-platform/core', '2.7', sprintf('Use "%s" instead of "%s".', ResourceMetadataCollectionFactoryInterface::class, ResourceMetadataFactoryInterface::class));
  35. }
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function createFromRequest(Request $request, bool $normalization, array $attributes = null): array
  41. {
  42. if (null === $attributes && !$attributes = RequestAttributesExtractor::extractAttributes($request)) {
  43. throw new RuntimeException('Request attributes are not valid.');
  44. }
  45. // TODO remove call to getContentType() when requiring symfony/http-foundation ≥ 6.2
  46. $contentTypeFormat = method_exists($request, 'getContentTypeFormat')
  47. ? $request->getContentTypeFormat()
  48. : $request->getContentType();
  49. // TODO: 3.0 change the condition to remove the ResourceMetadataFactorym only used to skip null values
  50. if (
  51. $this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface
  52. && (isset($attributes['operation_name']) || isset($attributes['operation']))
  53. ) {
  54. $operation = $attributes['operation'] ?? $this->resourceMetadataFactory->create($attributes['resource_class'])->getOperation($attributes['operation_name']);
  55. $context = $normalization ? ($operation->getNormalizationContext() ?? []) : ($operation->getDenormalizationContext() ?? []);
  56. $context['operation_name'] = $operation->getName();
  57. $context['operation'] = $operation;
  58. $context['resource_class'] = $attributes['resource_class'];
  59. // TODO: 3.0 becomes true by default
  60. $context['skip_null_values'] = $context['skip_null_values'] ?? $this->shouldSkipNullValues($attributes['resource_class'], $context['operation_name']);
  61. // TODO: remove in 3.0, operation type will not exist anymore
  62. $context['operation_type'] = $operation instanceof CollectionOperationInterface ? OperationType::COLLECTION : OperationType::ITEM;
  63. $context['iri_only'] = $context['iri_only'] ?? false;
  64. $context['request_uri'] = $request->getRequestUri();
  65. $context['uri'] = $request->getUri();
  66. $context['input'] = $operation->getInput();
  67. $context['output'] = $operation->getOutput();
  68. $context['types'] = $operation->getTypes();
  69. $context['uri_variables'] = [];
  70. foreach (array_keys($operation->getUriVariables() ?? []) as $parameterName) {
  71. $context['uri_variables'][$parameterName] = $request->attributes->get($parameterName);
  72. }
  73. if (!$normalization) {
  74. if (!isset($context['api_allow_update'])) {
  75. $context['api_allow_update'] = \in_array($method = $request->getMethod(), ['PUT', 'PATCH'], true);
  76. if ($context['api_allow_update'] && 'PATCH' === $method) {
  77. $context['deep_object_to_populate'] = $context['deep_object_to_populate'] ?? true;
  78. }
  79. }
  80. if ('csv' === $contentTypeFormat) {
  81. $context[CsvEncoder::AS_COLLECTION_KEY] = false;
  82. }
  83. }
  84. return $context;
  85. }
  86. /** @var ResourceMetadata $resourceMetadata */
  87. $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
  88. $key = $normalization ? 'normalization_context' : 'denormalization_context';
  89. if (isset($attributes['collection_operation_name'])) {
  90. $operationKey = 'collection_operation_name';
  91. $operationType = OperationType::COLLECTION;
  92. } elseif (isset($attributes['item_operation_name'])) {
  93. $operationKey = 'item_operation_name';
  94. $operationType = OperationType::ITEM;
  95. } else {
  96. $operationKey = 'subresource_operation_name';
  97. $operationType = OperationType::SUBRESOURCE;
  98. }
  99. $context = $resourceMetadata->getTypedOperationAttribute($operationType, $attributes[$operationKey], $key, [], true);
  100. $context['operation_type'] = $operationType;
  101. $context[$operationKey] = $attributes[$operationKey];
  102. $context['iri_only'] = $resourceMetadata->getAttribute('normalization_context')['iri_only'] ?? false;
  103. $context['input'] = $resourceMetadata->getTypedOperationAttribute($operationType, $attributes[$operationKey], 'input', null, true);
  104. $context['output'] = $resourceMetadata->getTypedOperationAttribute($operationType, $attributes[$operationKey], 'output', null, true);
  105. if (!$normalization) {
  106. if (!isset($context['api_allow_update'])) {
  107. $context['api_allow_update'] = \in_array($method = $request->getMethod(), ['PUT', 'PATCH'], true);
  108. if ($context['api_allow_update'] && 'PATCH' === $method) {
  109. $context['deep_object_to_populate'] = $context['deep_object_to_populate'] ?? true;
  110. }
  111. }
  112. if ('csv' === $contentTypeFormat) {
  113. $context[CsvEncoder::AS_COLLECTION_KEY] = false;
  114. }
  115. }
  116. $context['resource_class'] = $attributes['resource_class'];
  117. $context['request_uri'] = $request->getRequestUri();
  118. $context['uri'] = $request->getUri();
  119. if (isset($attributes['subresource_context'])) {
  120. $context['subresource_identifiers'] = [];
  121. foreach ($attributes['subresource_context']['identifiers'] as $parameterName => [$resourceClass]) {
  122. if (!isset($context['subresource_resources'][$resourceClass])) {
  123. $context['subresource_resources'][$resourceClass] = [];
  124. }
  125. $context['subresource_identifiers'][$parameterName] = $context['subresource_resources'][$resourceClass][$parameterName] = $request->attributes->get($parameterName);
  126. }
  127. }
  128. if (isset($attributes['subresource_property'])) {
  129. $context['subresource_property'] = $attributes['subresource_property'];
  130. $context['subresource_resource_class'] = $attributes['subresource_resource_class'] ?? null;
  131. }
  132. unset($context[DocumentationNormalizer::SWAGGER_DEFINITION_NAME]);
  133. if (isset($context['skip_null_values'])) {
  134. return $context;
  135. }
  136. // TODO: We should always use `skip_null_values` but changing this would be a BC break, for now use it only when `merge-patch+json` is activated on a Resource
  137. if (!$this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  138. foreach ($resourceMetadata->getItemOperations() as $operation) {
  139. if ('PATCH' === ($operation['method'] ?? '') && \in_array('application/merge-patch+json', $operation['input_formats']['json'] ?? [], true)) {
  140. $context['skip_null_values'] = true;
  141. break;
  142. }
  143. }
  144. } else {
  145. $context['skip_null_values'] = $this->shouldSkipNullValues($attributes['resource_class'], $attributes['operation_name']);
  146. }
  147. return $context;
  148. }
  149. /**
  150. * TODO: remove in 3.0, this will have no impact and skip_null_values will be default, no more resourceMetadataFactory call in this class.
  151. */
  152. private function shouldSkipNullValues(string $class, string $operationName): bool
  153. {
  154. if (!$this->resourceMetadataFactory) {
  155. return false;
  156. }
  157. $collection = $this->resourceMetadataFactory->create($class);
  158. foreach ($collection as $metadata) {
  159. foreach ($metadata->getOperations() as $operation) {
  160. if ('PATCH' === ($operation->getMethod() ?? '') && \in_array('application/merge-patch+json', $operation->getInputFormats()['json'] ?? [], true)) {
  161. return true;
  162. }
  163. }
  164. }
  165. return false;
  166. }
  167. }
  168. class_alias(SerializerContextBuilder::class, \ApiPlatform\Core\Serializer\SerializerContextBuilder::class);