vendor/api-platform/core/src/Hydra/Serializer/CollectionNormalizer.php line 62

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <[email protected]>
  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\Hydra\Serializer;
  12. use ApiPlatform\Api\IriConverterInterface;
  13. use ApiPlatform\Api\ResourceClassResolverInterface;
  14. use ApiPlatform\Api\UrlGeneratorInterface;
  15. use ApiPlatform\Core\Api\IriConverterInterface as LegacyIriConverterInterface;
  16. use ApiPlatform\Core\Api\OperationType;
  17. use ApiPlatform\JsonLd\ContextBuilderInterface;
  18. use ApiPlatform\JsonLd\Serializer\JsonLdContextTrait;
  19. use ApiPlatform\Metadata\CollectionOperationInterface;
  20. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  21. use ApiPlatform\Serializer\ContextTrait;
  22. use ApiPlatform\State\Pagination\PaginatorInterface;
  23. use ApiPlatform\State\Pagination\PartialPaginatorInterface;
  24. use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
  25. use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
  26. use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
  27. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  28. /**
  29.  * This normalizer handles collections.
  30.  *
  31.  * @author Kevin Dunglas <[email protected]>
  32.  * @author Samuel ROZE <[email protected]>
  33.  */
  34. final class CollectionNormalizer implements NormalizerInterfaceNormalizerAwareInterfaceCacheableSupportsMethodInterface
  35. {
  36.     use ContextTrait;
  37.     use JsonLdContextTrait;
  38.     use NormalizerAwareTrait;
  39.     public const FORMAT 'jsonld';
  40.     public const IRI_ONLY 'iri_only';
  41.     private $contextBuilder;
  42.     private $resourceClassResolver;
  43.     private $iriConverter;
  44.     private $resourceMetadataCollectionFactory;
  45.     private $defaultContext = [
  46.         self::IRI_ONLY => false,
  47.     ];
  48.     public function __construct(ContextBuilderInterface $contextBuilderResourceClassResolverInterface $resourceClassResolver$iriConverter, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory null, array $defaultContext = [])
  49.     {
  50.         $this->contextBuilder $contextBuilder;
  51.         $this->resourceClassResolver $resourceClassResolver;
  52.         if ($iriConverter instanceof LegacyIriConverterInterface) {
  53.             trigger_deprecation('api-platform/core''2.7'sprintf('Use an implementation of "%s" instead of "%s".'IriConverterInterface::class, LegacyIriConverterInterface::class));
  54.         }
  55.         $this->iriConverter $iriConverter;
  56.         $this->resourceMetadataCollectionFactory $resourceMetadataCollectionFactory;
  57.         $this->defaultContext array_merge($this->defaultContext$defaultContext);
  58.     }
  59.     /**
  60.      * {@inheritdoc}
  61.      */
  62.     public function supportsNormalization($data$format null, array $context = []): bool
  63.     {
  64.         return self::FORMAT === $format && is_iterable($data);
  65.     }
  66.     /**
  67.      * {@inheritdoc}
  68.      *
  69.      * @param iterable $object
  70.      */
  71.     public function normalize($object$format null, array $context = []): array
  72.     {
  73.         if (!isset($context['resource_class']) || isset($context['api_sub_level'])) {
  74.             return $this->normalizeRawCollection($object$format$context);
  75.         }
  76.         $resourceClass $this->resourceClassResolver->getResourceClass($object$context['resource_class']);
  77.         $context $this->initContext($resourceClass$context);
  78.         $data $this->addJsonLdContext($this->contextBuilder$resourceClass$context);
  79.         if ($this->iriConverter instanceof LegacyIriConverterInterface) {
  80.             // TODO: remove in 3.0
  81.             $data['@id'] = isset($context['operation_type']) && OperationType::SUBRESOURCE === $context['operation_type'] ? $this->iriConverter->getSubresourceIriFromResourceClass($resourceClass$context) : $this->iriConverter->getIriFromResourceClass($resourceClass);
  82.         } else {
  83.             $data['@id'] = $this->iriConverter->getIriFromResource($resourceClassUrlGeneratorInterface::ABS_PATH$context['operation'] ?? null$context);
  84.         }
  85.         $data['@type'] = 'hydra:Collection';
  86.         $data['hydra:member'] = [];
  87.         $iriOnly $context[self::IRI_ONLY] ?? $this->defaultContext[self::IRI_ONLY];
  88.         if ($this->resourceMetadataCollectionFactory && ($operation $context['operation'] ?? null) instanceof CollectionOperationInterface && ($itemUriTemplate $operation->getItemUriTemplate())) {
  89.             $context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation($operation->getItemUriTemplate());
  90.         } else {
  91.             unset($context['operation']);
  92.         }
  93.         unset($context['operation_name'], $context['uri_variables']);
  94.         foreach ($object as $obj) {
  95.             if ($iriOnly) {
  96.                 $data['hydra:member'][] = $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getIriFromItem($obj) : $this->iriConverter->getIriFromResource($obj);
  97.             } else {
  98.                 $data['hydra:member'][] = $this->normalizer->normalize($obj$format$context);
  99.             }
  100.         }
  101.         if ($object instanceof PaginatorInterface) {
  102.             $data['hydra:totalItems'] = $object->getTotalItems();
  103.         }
  104.         if (\is_array($object) || ($object instanceof \Countable && !$object instanceof PartialPaginatorInterface)) {
  105.             $data['hydra:totalItems'] = \count($object);
  106.         }
  107.         return $data;
  108.     }
  109.     /**
  110.      * {@inheritdoc}
  111.      */
  112.     public function hasCacheableSupportsMethod(): bool
  113.     {
  114.         return true;
  115.     }
  116.     /**
  117.      * Normalizes a raw collection (not API resources).
  118.      */
  119.     private function normalizeRawCollection(iterable $object, ?string $format, array $context): array
  120.     {
  121.         $data = [];
  122.         foreach ($object as $index => $obj) {
  123.             $data[$index] = $this->normalizer->normalize($obj$format$context);
  124.         }
  125.         return $data;
  126.     }
  127. }
  128. class_alias(CollectionNormalizer::class, \ApiPlatform\Core\Hydra\Serializer\CollectionNormalizer::class);