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

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