vendor/api-platform/core/src/JsonLd/Action/ContextAction.php line 27

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\Action;
  12. use ApiPlatform\Exception\OperationNotFoundException;
  13. use ApiPlatform\JsonLd\ContextBuilderInterface;
  14. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  15. use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. /**
  18.  * Generates JSON-LD contexts.
  19.  *
  20.  * @author Kévin Dunglas <dunglas@gmail.com>
  21.  */
  22. final class ContextAction
  23. {
  24.     public const RESERVED_SHORT_NAMES = [
  25.         'ConstraintViolationList' => true,
  26.         'Error' => true,
  27.     ];
  28.     public function __construct(private readonly ContextBuilderInterface $contextBuilder, private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory)
  29.     {
  30.     }
  31.     /**
  32.      * Generates a context according to the type requested.
  33.      *
  34.      * @throws NotFoundHttpException
  35.      */
  36.     public function __invoke(string $shortName): array
  37.     {
  38.         if ('Entrypoint' === $shortName) {
  39.             return ['@context' => $this->contextBuilder->getEntrypointContext()];
  40.         }
  41.         if (isset(self::RESERVED_SHORT_NAMES[$shortName])) {
  42.             return ['@context' => $this->contextBuilder->getBaseContext()];
  43.         }
  44.         foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
  45.             $resourceMetadataCollection $this->resourceMetadataCollectionFactory->create($resourceClass);
  46.             try {
  47.                 $resourceMetadataCollection $resourceMetadataCollection->getOperation();
  48.             } catch (OperationNotFoundException) {
  49.                 continue;
  50.             }
  51.             if ($shortName === $resourceMetadataCollection->getShortName()) {
  52.                 return ['@context' => $this->contextBuilder->getResourceContext($resourceClass)];
  53.             }
  54.         }
  55.         throw new NotFoundHttpException();
  56.     }
  57. }