vendor/api-platform/core/src/Hydra/EventListener/AddLinkHeaderListener.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\Hydra\EventListener;
  12. use ApiPlatform\Api\UrlGeneratorInterface as LegacyUrlGeneratorInterface;
  13. use ApiPlatform\JsonLd\ContextBuilder;
  14. use ApiPlatform\Metadata\UrlGeneratorInterface;
  15. use ApiPlatform\State\Util\CorsTrait;
  16. use Psr\Link\EvolvableLinkProviderInterface;
  17. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  18. use Symfony\Component\WebLink\GenericLinkProvider;
  19. use Symfony\Component\WebLink\Link;
  20. /**
  21.  * Adds the HTTP Link header pointing to the Hydra documentation.
  22.  *
  23.  * @author Kévin Dunglas <dunglas@gmail.com>
  24.  */
  25. final class AddLinkHeaderListener
  26. {
  27.     use CorsTrait;
  28.     public function __construct(private readonly UrlGeneratorInterface|LegacyUrlGeneratorInterface $urlGenerator)
  29.     {
  30.     }
  31.     /**
  32.      * Sends the Hydra header on each response.
  33.      */
  34.     public function onKernelResponse(ResponseEvent $event): void
  35.     {
  36.         $request $event->getRequest();
  37.         if (($operation $request->attributes->get('_api_operation')) && 'api_platform.symfony.main_controller' === $operation->getController()) {
  38.             return;
  39.         }
  40.         // Prevent issues with NelmioCorsBundle
  41.         if ($this->isPreflightRequest($request)) {
  42.             return;
  43.         }
  44.         $apiDocUrl $this->urlGenerator->generate('api_doc', ['_format' => 'jsonld'], UrlGeneratorInterface::ABS_URL);
  45.         $apiDocLink = new Link(ContextBuilder::HYDRA_NS.'apiDocumentation'$apiDocUrl);
  46.         $linkProvider $request->attributes->get('_api_platform_links', new GenericLinkProvider());
  47.         if (!$linkProvider instanceof EvolvableLinkProviderInterface) {
  48.             return;
  49.         }
  50.         foreach ($linkProvider->getLinks() as $link) {
  51.             if ($link->getHref() === $apiDocUrl) {
  52.                 return;
  53.             }
  54.         }
  55.         $request->attributes->set('_api_platform_links'$linkProvider->withLink($apiDocLink));
  56.     }
  57. }