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

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  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 <[email protected]>
  22. *
  23. * @final
  24. */
  25. class AddLinkHeaderListener implements EventSubscriberInterface
  26. {
  27. private $serializer;
  28. public function __construct()
  29. {
  30. $this->serializer = new HttpHeaderSerializer();
  31. }
  32. public function onKernelResponse(ResponseEvent $event)
  33. {
  34. if (!$event->isMainRequest()) {
  35. return;
  36. }
  37. $linkProvider = $event->getRequest()->attributes->get('_links');
  38. if (!$linkProvider instanceof LinkProviderInterface || !$links = $linkProvider->getLinks()) {
  39. return;
  40. }
  41. $event->getResponse()->headers->set('Link', $this->serializer->serialize($links), false);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public static function getSubscribedEvents(): array
  47. {
  48. return [KernelEvents::RESPONSE => 'onKernelResponse'];
  49. }
  50. }