<?php
namespace App\EventListener;
use App\enum\Events;
use App\Event\ResponseInterruptEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
class ResponseInterruptSubscriber implements EventSubscriberInterface
{
private JsonResponse $response;
private bool $doInterrupt = false;
public static function getSubscribedEvents(): array
{
return [
Events::RESPONSE_INTERRUPT => 'onResponseInterrupt',
ResponseEvent::class => 'onKernelResponse',
];
}
public function onResponseInterrupt(ResponseInterruptEvent $event): void
{
if ($event->shouldInterrupt()) {
$this->response = new JsonResponse($event->getBody(), $event->getStatus());
$this->doInterrupt = true;
}
}
public function onKernelResponse(ResponseEvent $event): void
{
if ($this->doInterrupt) {
$event->setResponse($this->response);
$event->stopPropagation();
}
}
}