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

  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\Symfony\EventListener;
  12. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  13. use ApiPlatform\Util\CorsTrait;
  14. use ApiPlatform\Util\OperationRequestInitiatorTrait;
  15. use ApiPlatform\Util\RequestAttributesExtractor;
  16. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  17. use Symfony\Component\Mercure\Discovery;
  18. use Symfony\Component\WebLink\Link;
  19. /**
  20.  * Adds the HTTP Link header pointing to the Mercure hub for resources having their updates dispatched.
  21.  *
  22.  * @author Kévin Dunglas <dunglas@gmail.com>
  23.  */
  24. final class AddLinkHeaderListener
  25. {
  26.     use CorsTrait;
  27.     use OperationRequestInitiatorTrait;
  28.     public function __construct(private readonly Discovery $discovery, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory null)
  29.     {
  30.         $this->resourceMetadataCollectionFactory $resourceMetadataCollectionFactory;
  31.     }
  32.     /**
  33.      * Sends the Mercure header on each response.
  34.      */
  35.     public function onKernelResponse(ResponseEvent $event): void
  36.     {
  37.         $request $event->getRequest();
  38.         $operation $this->initializeOperation($request);
  39.         if (
  40.             null === $request->attributes->get('_api_resource_class') ||
  41.             !($attributes RequestAttributesExtractor::extractAttributes($request))
  42.         ) {
  43.             return;
  44.         }
  45.         $mercure $operation?->getMercure() ?? ($attributes['mercure'] ?? false);
  46.         if (!$mercure) {
  47.             return;
  48.         }
  49.         $hub \is_array($mercure) ? ($mercure['hub'] ?? null) : null;
  50.         $this->discovery->addLink($request$hub);
  51.     }
  52. }