vendor/symfony/ux-turbo/Stream/AddTurboStreamFormatSubscriber.php line 42

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\UX\Turbo\Stream;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpKernel\Event\RequestEvent;
  13. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. /**
  16.  * Detects if it's a Turbo Stream request and sets the format accordingly.
  17.  *
  18.  * @author Kévin Dunglas <kevin@dunglas.fr>
  19.  *
  20.  * @experimental
  21.  */
  22. final class AddTurboStreamFormatSubscriber implements EventSubscriberInterface
  23. {
  24.     public function onKernelRequest(RequestEvent $event): void
  25.     {
  26.         $request $event->getRequest();
  27.         if (!($accept $request->headers->get('Accept')) || !== strpos($acceptTurboStreamResponse::STREAM_MEDIA_TYPE)) {
  28.             return;
  29.         }
  30.         $request->setFormat(TurboStreamResponse::STREAM_FORMATTurboStreamResponse::STREAM_MEDIA_TYPE);
  31.         $request->setRequestFormat(TurboStreamResponse::STREAM_FORMAT);
  32.     }
  33.     /**
  34.      * Prevents issues with Turbo Frames when sending a response that isn't in the Turbo Stream format.
  35.      */
  36.     public function onKernelResponse(ResponseEvent $event): void
  37.     {
  38.         $response $event->getResponse();
  39.         if ($response instanceof TurboStreamResponse) {
  40.             return;
  41.         }
  42.         $request $event->getRequest();
  43.         if (TurboStreamResponse::STREAM_FORMAT === $request->getRequestFormat(null)) {
  44.             $request->setRequestFormat(null);
  45.         }
  46.     }
  47.     /**
  48.      * Executed before AddRequestFormatsListener and ResponseListener.
  49.      *
  50.      * @return array<string, array>
  51.      */
  52.     public static function getSubscribedEvents(): array
  53.     {
  54.         return [
  55.             KernelEvents::REQUEST => ['onKernelRequest'110],
  56.             KernelEvents::RESPONSE => ['onKernelResponse'10],
  57.         ];
  58.     }
  59. }