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

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 $requestbool $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: 3.0 change the condition to remove the ResourceMetadataFactorym only used to skip null values
  46.         if (
  47.             $this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface
  48.             && (isset($attributes['operation_name']) || isset($attributes['operation']))
  49.         ) {
  50.             $operation $attributes['operation'] ?? $this->resourceMetadataFactory->create($attributes['resource_class'])->getOperation($attributes['operation_name']);
  51.             $context $normalization ? ($operation->getNormalizationContext() ?? []) : ($operation->getDenormalizationContext() ?? []);
  52.             $context['operation_name'] = $operation->getName();
  53.             $context['operation'] = $operation;
  54.             $context['resource_class'] = $attributes['resource_class'];
  55.             // TODO: 3.0 becomes true by default
  56.             $context['skip_null_values'] = $context['skip_null_values'] ?? $this->shouldSkipNullValues($attributes['resource_class'], $context['operation_name']);
  57.             // TODO: remove in 3.0, operation type will not exist anymore
  58.             $context['operation_type'] = $operation instanceof CollectionOperationInterface OperationType::COLLECTION OperationType::ITEM;
  59.             $context['iri_only'] = $context['iri_only'] ?? false;
  60.             $context['request_uri'] = $request->getRequestUri();
  61.             $context['uri'] = $request->getUri();
  62.             $context['input'] = $operation->getInput();
  63.             $context['output'] = $operation->getOutput();
  64.             $context['types'] = $operation->getTypes();
  65.             $context['uri_variables'] = [];
  66.             foreach (array_keys($operation->getUriVariables() ?? []) as $parameterName) {
  67.                 $context['uri_variables'][$parameterName] = $request->attributes->get($parameterName);
  68.             }
  69.             if (!$normalization) {
  70.                 if (!isset($context['api_allow_update'])) {
  71.                     $context['api_allow_update'] = \in_array($method $request->getMethod(), ['PUT''PATCH'], true);
  72.                     if ($context['api_allow_update'] && 'PATCH' === $method) {
  73.                         $context['deep_object_to_populate'] = $context['deep_object_to_populate'] ?? true;
  74.                     }
  75.                 }
  76.                 if ('csv' === $request->getContentType()) {
  77.                     $context[CsvEncoder::AS_COLLECTION_KEY] = false;
  78.                 }
  79.             }
  80.             return $context;
  81.         }
  82.         /** @var ResourceMetadata $resourceMetadata */
  83.         $resourceMetadata $this->resourceMetadataFactory->create($attributes['resource_class']);
  84.         $key $normalization 'normalization_context' 'denormalization_context';
  85.         if (isset($attributes['collection_operation_name'])) {
  86.             $operationKey 'collection_operation_name';
  87.             $operationType OperationType::COLLECTION;
  88.         } elseif (isset($attributes['item_operation_name'])) {
  89.             $operationKey 'item_operation_name';
  90.             $operationType OperationType::ITEM;
  91.         } else {
  92.             $operationKey 'subresource_operation_name';
  93.             $operationType OperationType::SUBRESOURCE;
  94.         }
  95.         $context $resourceMetadata->getTypedOperationAttribute($operationType$attributes[$operationKey], $key, [], true);
  96.         $context['operation_type'] = $operationType;
  97.         $context[$operationKey] = $attributes[$operationKey];
  98.         $context['iri_only'] = $resourceMetadata->getAttribute('normalization_context')['iri_only'] ?? false;
  99.         $context['input'] = $resourceMetadata->getTypedOperationAttribute($operationType$attributes[$operationKey], 'input'nulltrue);
  100.         $context['output'] = $resourceMetadata->getTypedOperationAttribute($operationType$attributes[$operationKey], 'output'nulltrue);
  101.         if (!$normalization) {
  102.             if (!isset($context['api_allow_update'])) {
  103.                 $context['api_allow_update'] = \in_array($method $request->getMethod(), ['PUT''PATCH'], true);
  104.                 if ($context['api_allow_update'] && 'PATCH' === $method) {
  105.                     $context['deep_object_to_populate'] = $context['deep_object_to_populate'] ?? true;
  106.                 }
  107.             }
  108.             if ('csv' === $request->getContentType()) {
  109.                 $context[CsvEncoder::AS_COLLECTION_KEY] = false;
  110.             }
  111.         }
  112.         $context['resource_class'] = $attributes['resource_class'];
  113.         $context['request_uri'] = $request->getRequestUri();
  114.         $context['uri'] = $request->getUri();
  115.         if (isset($attributes['subresource_context'])) {
  116.             $context['subresource_identifiers'] = [];
  117.             foreach ($attributes['subresource_context']['identifiers'] as $parameterName => [$resourceClass]) {
  118.                 if (!isset($context['subresource_resources'][$resourceClass])) {
  119.                     $context['subresource_resources'][$resourceClass] = [];
  120.                 }
  121.                 $context['subresource_identifiers'][$parameterName] = $context['subresource_resources'][$resourceClass][$parameterName] = $request->attributes->get($parameterName);
  122.             }
  123.         }
  124.         if (isset($attributes['subresource_property'])) {
  125.             $context['subresource_property'] = $attributes['subresource_property'];
  126.             $context['subresource_resource_class'] = $attributes['subresource_resource_class'] ?? null;
  127.         }
  128.         unset($context[DocumentationNormalizer::SWAGGER_DEFINITION_NAME]);
  129.         if (isset($context['skip_null_values'])) {
  130.             return $context;
  131.         }
  132.         // 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
  133.         if (!$this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  134.             foreach ($resourceMetadata->getItemOperations() as $operation) {
  135.                 if ('PATCH' === ($operation['method'] ?? '') && \in_array('application/merge-patch+json'$operation['input_formats']['json'] ?? [], true)) {
  136.                     $context['skip_null_values'] = true;
  137.                     break;
  138.                 }
  139.             }
  140.         } else {
  141.             $context['skip_null_values'] = $this->shouldSkipNullValues($attributes['resource_class'], $attributes['operation_name']);
  142.         }
  143.         return $context;
  144.     }
  145.     /**
  146.      * TODO: remove in 3.0, this will have no impact and skip_null_values will be default, no more resourceMetadataFactory call in this class.
  147.      */
  148.     private function shouldSkipNullValues(string $classstring $operationName): bool
  149.     {
  150.         if (!$this->resourceMetadataFactory) {
  151.             return false;
  152.         }
  153.         $collection $this->resourceMetadataFactory->create($class);
  154.         foreach ($collection as $metadata) {
  155.             foreach ($metadata->getOperations() as $operation) {
  156.                 if ('PATCH' === ($operation->getMethod() ?? '') && \in_array('application/merge-patch+json'$operation->getInputFormats()['json'] ?? [], true)) {
  157.                     return true;
  158.                 }
  159.             }
  160.         }
  161.         return false;
  162.     }
  163. }
  164. class_alias(SerializerContextBuilder::class, \ApiPlatform\Core\Serializer\SerializerContextBuilder::class);