<?php
namespace App\EventSubscriber\Api;
use App\Controller\Api\AbstractApiController;
use App\Helper\Api\Entity\JsonResponseDataContainer;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\LogoutEvent;
/**
* Returns response after successful logout
*
* @package API
* @api
*/
class LogoutSubscriber 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 PhpArrayShapeAttributeCanBeAddedInspection
* @noinspection PhpUnused
*/
public static function getSubscribedEvents(): array
{
return [
LogoutEvent::class => [
['onLogout', 0]
]
];
}
/**
* Creates a JsonResponse when logout event is dispatched.
*
* @param LogoutEvent $event Logout event.
* @return void
* @noinspection PhpUnused
* @api
*/
public function onLogout(LogoutEvent $event): void
{
$token = $event->getToken();
/* @var UsernamePasswordToken $token */
// only handle for API routes and main firewall
if (preg_match('/^\/api\//', $event->getRequest()->getRequestUri()) &&
$token->getFirewallName() === 'main') {
$container = new JsonResponseDataContainer();
$container->addData(
[AbstractApiController::JSON_RESPONSE_PARAMETER_NAME_MESSAGE => $this->t('logout.successful')]
);
$event->setResponse(new JsonResponse($container->getJsonString(), Response::HTTP_OK, [], true));
}
}
}