vendor/api-platform/core/src/Hydra/EventListener/AddLinkHeaderListener.php line 39

  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;
  13. use ApiPlatform\JsonLd\ContextBuilder;
  14. use ApiPlatform\Util\CorsTrait;
  15. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  16. use Symfony\Component\WebLink\GenericLinkProvider;
  17. use Symfony\Component\WebLink\Link;
  18. /**
  19.  * Adds the HTTP Link header pointing to the Hydra documentation.
  20.  *
  21.  * @author Kévin Dunglas <dunglas@gmail.com>
  22.  */
  23. final class AddLinkHeaderListener
  24. {
  25.     use CorsTrait;
  26.     public function __construct(private readonly UrlGeneratorInterface $urlGenerator)
  27.     {
  28.     }
  29.     /**
  30.      * Sends the Hydra header on each response.
  31.      */
  32.     public function onKernelResponse(ResponseEvent $event): void
  33.     {
  34.         $request $event->getRequest();
  35.         // Prevent issues with NelmioCorsBundle
  36.         if ($this->isPreflightRequest($request)) {
  37.             return;
  38.         }
  39.         $apiDocUrl $this->urlGenerator->generate('api_doc', ['_format' => 'jsonld'], UrlGeneratorInterface::ABS_URL);
  40.         $link = new Link(ContextBuilder::HYDRA_NS.'apiDocumentation'$apiDocUrl);
  41.         if (null === $linkProvider $request->attributes->get('_links')) {
  42.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  43.             return;
  44.         }
  45.         $request->attributes->set('_links'$linkProvider->withLink($link));
  46.     }
  47. }