src/EventListener/ResponseInterruptSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\enum\Events;
  4. use App\Event\ResponseInterruptEvent;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. class ResponseInterruptSubscriber implements EventSubscriberInterface
  9. {
  10.     private JsonResponse $response;
  11.     private bool $doInterrupt false;
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         return [
  15.             Events::RESPONSE_INTERRUPT => 'onResponseInterrupt',
  16.             ResponseEvent::class => 'onKernelResponse',
  17.         ];
  18.     }
  19.     public function onResponseInterrupt(ResponseInterruptEvent $event): void
  20.     {
  21.         if ($event->shouldInterrupt()) {
  22.             $this->response = new JsonResponse($event->getBody(), $event->getStatus());
  23.             $this->doInterrupt true;
  24.         }
  25.     }
  26.     public function onKernelResponse(ResponseEvent $event): void
  27.     {
  28.         if ($this->doInterrupt) {
  29.             $event->setResponse($this->response);
  30.             $event->stopPropagation();
  31.         }
  32.     }
  33. }