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 <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\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 <dunglas@gmail.com>
  32. * @author Samuel ROZE <samuel.roze@gmail.com>
  33. */
  34. final class CollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface, CacheableSupportsMethodInterface
  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 $contextBuilder, ResourceClassResolverInterface $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. $context['api_collection_sub_level'] = true;
  79. $data = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
  80. if ($this->iriConverter instanceof LegacyIriConverterInterface) {
  81. // TODO: remove in 3.0
  82. $data['@id'] = isset($context['operation_type']) && OperationType::SUBRESOURCE === $context['operation_type'] ? $this->iriConverter->getSubresourceIriFromResourceClass($resourceClass, $context) : $this->iriConverter->getIriFromResourceClass($resourceClass);
  83. } else {
  84. $data['@id'] = $this->iriConverter->getIriFromResource($resourceClass, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
  85. }
  86. $data['@type'] = 'hydra:Collection';
  87. $data['hydra:member'] = [];
  88. $iriOnly = $context[self::IRI_ONLY] ?? $this->defaultContext[self::IRI_ONLY];
  89. // We need to keep this operation for serialization groups for later
  90. if (isset($context['operation'])) {
  91. $context['root_operation'] = $context['operation'];
  92. }
  93. if (isset($context['operation_name'])) {
  94. $context['root_operation_name'] = $context['operation_name'];
  95. }
  96. if ($this->resourceMetadataCollectionFactory && ($operation = $context['operation'] ?? null) instanceof CollectionOperationInterface && ($itemUriTemplate = $operation->getItemUriTemplate())) {
  97. $context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation($operation->getItemUriTemplate());
  98. } else {
  99. unset($context['operation']);
  100. }
  101. unset($context['operation_name'], $context['uri_variables']);
  102. foreach ($object as $obj) {
  103. if ($iriOnly) {
  104. $data['hydra:member'][] = $this->iriConverter instanceof LegacyIriConverterInterface ? $this->iriConverter->getIriFromItem($obj) : $this->iriConverter->getIriFromResource($obj);
  105. } else {
  106. $data['hydra:member'][] = $this->normalizer->normalize($obj, $format, $context);
  107. }
  108. }
  109. if ($object instanceof PaginatorInterface) {
  110. $data['hydra:totalItems'] = $object->getTotalItems();
  111. }
  112. if (\is_array($object) || ($object instanceof \Countable && !$object instanceof PartialPaginatorInterface)) {
  113. $data['hydra:totalItems'] = \count($object);
  114. }
  115. return $data;
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function hasCacheableSupportsMethod(): bool
  121. {
  122. return true;
  123. }
  124. /**
  125. * Normalizes a raw collection (not API resources).
  126. */
  127. private function normalizeRawCollection(iterable $object, ?string $format, array $context): array
  128. {
  129. $data = [];
  130. foreach ($object as $index => $obj) {
  131. $data[$index] = $this->normalizer->normalize($obj, $format, $context);
  132. }
  133. return $data;
  134. }
  135. }
  136. class_alias(CollectionNormalizer::class, \ApiPlatform\Core\Hydra\Serializer\CollectionNormalizer::class);