src/EventSubscriber/Api/LogoutSubscriber.php line 60

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Api;
  3. use App\Controller\Api\AbstractApiController;
  4. use App\Helper\Api\Entity\JsonResponseDataContainer;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  8. use Symfony\Component\Security\Http\Event\LogoutEvent;
  9. /**
  10.  * Returns response after successful logout
  11.  *
  12.  * @package API
  13.  * @api
  14.  */
  15. class LogoutSubscriber extends AbstractSubscriber
  16. {
  17.     /**
  18.      * Returns an array of event names this subscriber wants to listen to.
  19.      *
  20.      * The array keys are event names and the value can be:
  21.      *
  22.      *  * The method name to call (priority defaults to 0)
  23.      *  * An array composed of the method name to call and the priority
  24.      *  * An array of arrays composed of the method names to call and respective
  25.      *    priorities, or 0 if unset
  26.      *
  27.      * For instance:
  28.      *
  29.      *  * ['eventName' => 'methodName']
  30.      *  * ['eventName' => ['methodName', $priority]]
  31.      *  * ['eventName' => [['methodName1', $priority], ['methodName2']]]
  32.      *
  33.      * The code must not depend on runtime state as it will only be called at compile time.
  34.      * All logic depending on runtime state must be put into the individual methods handling the events.
  35.      *
  36.      * @noinspection PhpArrayShapeAttributeCanBeAddedInspection
  37.      * @noinspection PhpUnused
  38.      */
  39.     public static function getSubscribedEvents(): array
  40.     {
  41.         return [
  42.             LogoutEvent::class => [
  43.                 ['onLogout'0]
  44.             ]
  45.         ];
  46.     }
  47.     /**
  48.      * Creates a JsonResponse when logout event is dispatched.
  49.      *
  50.      * @param LogoutEvent $event Logout event.
  51.      * @return void
  52.      * @noinspection PhpUnused
  53.      * @api
  54.      */
  55.     public function onLogout(LogoutEvent $event): void
  56.     {
  57.         $token $event->getToken();
  58.         /* @var UsernamePasswordToken $token */
  59.         // only handle for API routes and main firewall
  60.         if (preg_match('/^\/api\//'$event->getRequest()->getRequestUri()) &&
  61.             $token->getFirewallName() === 'main') {
  62.             $container = new JsonResponseDataContainer();
  63.             $container->addData(
  64.                 [AbstractApiController::JSON_RESPONSE_PARAMETER_NAME_MESSAGE => $this->t('logout.successful')]
  65.             );
  66.             $event->setResponse(new JsonResponse($container->getJsonString(), Response::HTTP_OK, [], true));
  67.         }
  68.     }
  69. }