vendor/symfony/web-link/EventListener/AddLinkHeaderListener.php line 37

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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. namespace Symfony\Component\WebLink\EventListener;
  11. use Psr\Link\LinkProviderInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\WebLink\HttpHeaderSerializer;
  16. // Help opcache.preload discover always-needed symbols
  17. class_exists(HttpHeaderSerializer::class);
  18. /**
  19. * Adds the Link HTTP header to the response.
  20. *
  21. * @author Kévin Dunglas <dunglas@gmail.com>
  22. *
  23. * @final
  24. */
  25. class AddLinkHeaderListener implements EventSubscriberInterface
  26. {
  27. public function __construct(
  28. private readonly HttpHeaderSerializer $serializer = new HttpHeaderSerializer(),
  29. ) {
  30. }
  31. public function onKernelResponse(ResponseEvent $event): void
  32. {
  33. if (!$event->isMainRequest()) {
  34. return;
  35. }
  36. $linkProvider = $event->getRequest()->attributes->get('_links');
  37. if (!$linkProvider instanceof LinkProviderInterface || !$links = $linkProvider->getLinks()) {
  38. return;
  39. }
  40. $event->getResponse()->headers->set('Link', $this->serializer->serialize($links), false);
  41. }
  42. public static function getSubscribedEvents(): array
  43. {
  44. return [KernelEvents::RESPONSE => 'onKernelResponse'];
  45. }
  46. }