<?php
namespace App\EventSubscriber\Api;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Subscriber to remove sf_redirect cookies on certain HTTP responses.
*
* @package API
* @internal
*/
class RedirectCookieSubscriber extends AbstractSubscriber
{
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* The code must not depend on runtime state as it will only be called at compile time.
* All logic depending on runtime state must be put into the individual methods handling the events.
*
* @noinspection PhpUnused
*/
public static function getSubscribedEvents(): array
{
return [
/**
* Must be registered after (i.e. with a lower priority than) {@see ProfilerListener::onKernelResponse())
* listener (currently -100 by bin/console debug:event)
*/
KernelEvents::RESPONSE => [
['onKernelResponse', -101]
]
];
}
/**
* Remove sf_redirect cookie on certain HTTP responses.
*
* @param ResponseEvent $event Response event.
* @return void
* @noinspection PhpUnused
*/
public function onKernelResponse(ResponseEvent $event): void
{
$request = $event->getRequest();
$response = $event->getResponse();
// only handle API routes, create/redirect requests and HTTP 201/307 status codes
if (str_starts_with($request->getRequestUri(), '/api/') && (
(
str_ends_with($request->attributes->get('_route'), 'create') &&
$response->getStatusCode() === Response::HTTP_CREATED
) ||
(
str_ends_with($request->attributes->get('_route'), 'default') &&
$response->getStatusCode() === Response::HTTP_TEMPORARY_REDIRECT
)
)) {
$response->headers->removeCookie('sf_redirect');
}
}
}