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

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;
  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.     private $urlGenerator;
  27.     public function __construct(UrlGeneratorInterface $urlGenerator)
  28.     {
  29.         $this->urlGenerator $urlGenerator;
  30.     }
  31.     /**
  32.      * Sends the Hydra header on each response.
  33.      */
  34.     public function onKernelResponse(ResponseEvent $event): void
  35.     {
  36.         $request $event->getRequest();
  37.         // Prevent issues with NelmioCorsBundle
  38.         if ($this->isPreflightRequest($request)) {
  39.             return;
  40.         }
  41.         $apiDocUrl $this->urlGenerator->generate('api_doc', ['_format' => 'jsonld'], UrlGeneratorInterface::ABS_URL);
  42.         $link = new Link(ContextBuilder::HYDRA_NS.'apiDocumentation'$apiDocUrl);
  43.         if (null === $linkProvider $request->attributes->get('_links')) {
  44.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  45.             return;
  46.         }
  47.         $request->attributes->set('_links'$linkProvider->withLink($link));
  48.     }
  49. }
  50. class_alias(AddLinkHeaderListener::class, \ApiPlatform\Core\Hydra\EventListener\AddLinkHeaderListener::class);