vendor/api-platform/core/src/JsonLd/ContextBuilder.php line 76

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\JsonLd;
  12. use ApiPlatform\Api\IriConverterInterface;
  13. use ApiPlatform\Api\UrlGeneratorInterface;
  14. use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface as LegacyPropertyMetadataFactoryInterface;
  15. use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface as LegacyPropertyNameCollectionFactoryInterface;
  16. use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
  17. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  18. use ApiPlatform\Metadata\ApiProperty;
  19. use ApiPlatform\Metadata\HttpOperation;
  20. use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
  21. use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
  22. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  23. use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
  24. use ApiPlatform\Util\ClassInfoTrait;
  25. use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
  26. /**
  27. * {@inheritdoc}
  28. * TODO: 3.0 simplify or remove the class.
  29. *
  30. * @author Kévin Dunglas <dunglas@gmail.com>
  31. */
  32. final class ContextBuilder implements AnonymousContextBuilderInterface
  33. {
  34. use ClassInfoTrait;
  35. public const FORMAT = 'jsonld';
  36. private $resourceNameCollectionFactory;
  37. /**
  38. * @param ResourceMetadataFactoryInterface|ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory
  39. */
  40. private $resourceMetadataFactory;
  41. /**
  42. * @var LegacyPropertyNameCollectionFactoryInterface|PropertyNameCollectionFactoryInterface
  43. */
  44. private $propertyNameCollectionFactory;
  45. /**
  46. * @var LegacyPropertyMetadataFactoryInterface|PropertyMetadataFactoryInterface
  47. */
  48. private $propertyMetadataFactory;
  49. private $urlGenerator;
  50. /**
  51. * @var NameConverterInterface|null
  52. */
  53. private $nameConverter;
  54. private $iriConverter;
  55. public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, $resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, UrlGeneratorInterface $urlGenerator, NameConverterInterface $nameConverter = null, IriConverterInterface $iriConverter = null)
  56. {
  57. $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
  58. $this->resourceMetadataFactory = $resourceMetadataFactory;
  59. $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
  60. $this->propertyMetadataFactory = $propertyMetadataFactory;
  61. $this->urlGenerator = $urlGenerator;
  62. $this->nameConverter = $nameConverter;
  63. $this->iriConverter = $iriConverter;
  64. if ($resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  65. trigger_deprecation('api-platform/core', '2.7', sprintf('Use "%s" instead of "%s".', ResourceMetadataCollectionFactoryInterface::class, ResourceMetadataFactoryInterface::class));
  66. }
  67. }
  68. public function getBaseContext(int $referenceType = UrlGeneratorInterface::ABS_URL): array
  69. {
  70. return [
  71. '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
  72. 'hydra' => self::HYDRA_NS,
  73. ];
  74. }
  75. public function getEntrypointContext(int $referenceType = UrlGeneratorInterface::ABS_PATH): array
  76. {
  77. $context = $this->getBaseContext($referenceType);
  78. foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
  79. // TODO: remove in 3.0
  80. if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  81. $shortName = $this->resourceMetadataFactory->create($resourceClass)->getShortName();
  82. } else {
  83. $shortName = $this->resourceMetadataFactory->create($resourceClass)[0]->getShortName();
  84. }
  85. $resourceName = lcfirst($shortName);
  86. $context[$resourceName] = [
  87. '@id' => 'Entrypoint/'.$resourceName,
  88. '@type' => '@id',
  89. ];
  90. }
  91. return $context;
  92. }
  93. public function getResourceContext(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): array
  94. {
  95. // TODO: Remove in 3.0
  96. if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  97. $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
  98. if (null === $shortName = $resourceMetadata->getShortName()) {
  99. return [];
  100. }
  101. if ($resourceMetadata->getAttribute('normalization_context')['iri_only'] ?? false) {
  102. $context = $this->getBaseContext($referenceType);
  103. $context['hydra:member']['@type'] = '@id';
  104. return $context;
  105. }
  106. return $this->getResourceContextWithShortname($resourceClass, $referenceType, $shortName);
  107. }
  108. $operation = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
  109. if (null === $shortName = $operation->getShortName()) {
  110. return [];
  111. }
  112. if ($operation->getNormalizationContext()['iri_only'] ?? false) {
  113. $context = $this->getBaseContext($referenceType);
  114. $context['hydra:member']['@type'] = '@id';
  115. return $context;
  116. }
  117. return $this->getResourceContextWithShortname($resourceClass, $referenceType, $shortName, $operation);
  118. }
  119. public function getResourceContextUri(string $resourceClass, int $referenceType = null): string
  120. {
  121. // TODO: remove in 3.0
  122. if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  123. $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
  124. if (null === $referenceType) {
  125. $referenceType = $resourceMetadata->getAttribute('url_generation_strategy');
  126. }
  127. return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()], $referenceType);
  128. }
  129. $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass)[0];
  130. if (null === $referenceType) {
  131. $referenceType = $resourceMetadata->getUrlGenerationStrategy();
  132. }
  133. return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()], $referenceType);
  134. }
  135. public function getAnonymousResourceContext($object, array $context = [], int $referenceType = UrlGeneratorInterface::ABS_PATH): array
  136. {
  137. $outputClass = $this->getObjectClass($object);
  138. $shortName = (new \ReflectionClass($outputClass))->getShortName();
  139. $jsonLdContext = [
  140. '@context' => $this->getResourceContextWithShortname(
  141. $outputClass,
  142. $referenceType,
  143. $shortName
  144. ),
  145. '@type' => $shortName,
  146. ];
  147. if (!isset($context['iri']) || false !== $context['iri']) {
  148. // Not using an IriConverter here is deprecated in 2.7, avoid spl_object_hash as it may collide
  149. if (isset($this->iriConverter)) {
  150. $jsonLdContext['@id'] = $context['iri'] ?? $this->iriConverter->getIriFromResource($object);
  151. } else {
  152. $jsonLdContext['@id'] = $context['iri'] ?? '/.well-known/genid/'.bin2hex(random_bytes(10));
  153. }
  154. }
  155. if ($this->iriConverter && isset($context['gen_id']) && true === $context['gen_id']) {
  156. $jsonLdContext['@id'] = $this->iriConverter->getIriFromResource($object);
  157. }
  158. if (false === ($context['iri'] ?? null)) {
  159. trigger_deprecation('api-platform/core', '2.7', 'An anonymous resource will use a Skolem IRI in API Platform 3.0. Use #[ApiProperty(genId: false)] to keep this behavior in 3.0.');
  160. }
  161. if ($context['has_context'] ?? false) {
  162. unset($jsonLdContext['@context']);
  163. }
  164. // here the object can be different from the resource given by the $context['api_resource'] value
  165. if (isset($context['api_resource'])) {
  166. if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  167. $jsonLdContext['@type'] = $this->resourceMetadataFactory->create($this->getObjectClass($context['api_resource']))->getShortName();
  168. } else {
  169. $jsonLdContext['@type'] = $this->resourceMetadataFactory->create($this->getObjectClass($context['api_resource']))[0]->getShortName();
  170. }
  171. }
  172. return $jsonLdContext;
  173. }
  174. private function getResourceContextWithShortname(string $resourceClass, int $referenceType, string $shortName, HttpOperation $operation = null): array
  175. {
  176. $context = $this->getBaseContext($referenceType);
  177. if ($this->propertyMetadataFactory instanceof LegacyPropertyMetadataFactoryInterface) {
  178. $propertyContext = [];
  179. } else {
  180. $propertyContext = $operation ? ['normalization_groups' => $operation->getNormalizationContext()['groups'] ?? null, 'denormalization_groups' => $operation->getDenormalizationContext()['groups'] ?? null] : ['normalization_groups' => [], 'denormalization_groups' => []];
  181. }
  182. foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
  183. /** @var PropertyMetadata|ApiProperty */
  184. $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $propertyContext);
  185. if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) {
  186. continue;
  187. }
  188. $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $resourceClass, self::FORMAT) : $propertyName;
  189. if ($propertyMetadata instanceof PropertyMetadata) {
  190. $jsonldContext = ($propertyMetadata->getAttributes() ?? [])['jsonld_context'] ?? [];
  191. $id = $propertyMetadata->getIri();
  192. } else {
  193. $jsonldContext = $propertyMetadata->getJsonldContext() ?? [];
  194. if ($id = $propertyMetadata->getIris()) {
  195. $id = 1 === \count($id) ? $id[0] : $id;
  196. }
  197. }
  198. if (!$id) {
  199. $id = sprintf('%s/%s', $shortName, $convertedName);
  200. }
  201. if (false === $propertyMetadata->isReadableLink()) {
  202. $jsonldContext += [
  203. '@id' => $id,
  204. '@type' => '@id',
  205. ];
  206. }
  207. if (empty($jsonldContext)) {
  208. $context[$convertedName] = $id;
  209. } else {
  210. $context[$convertedName] = $jsonldContext + [
  211. '@id' => $id,
  212. ];
  213. }
  214. }
  215. return $context;
  216. }
  217. }
  218. class_alias(ContextBuilder::class, \ApiPlatform\Core\JsonLd\ContextBuilder::class);