src/EventListener/AuthenticationListener.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\User\ShopUser;
  4. use App\Manager\Cart\CartManager;
  5. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  8. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  9. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  10. class AuthenticationListener
  11. {
  12.     private $session;
  13.     private $tokenStorage;
  14.     private $authorizationChecker;
  15.     public function __construct(SessionInterface              $session,
  16.                                 TokenStorageInterface         $tokenStorage,
  17.                                 AuthorizationCheckerInterface $authorizationChecker)
  18.     {
  19.         $this->session $session;
  20.         $this->tokenStorage $tokenStorage;
  21.         $this->authorizationChecker $authorizationChecker;
  22.     }
  23.     public function onAuthenticationSuccess(InteractiveLoginEvent $event)
  24.     {
  25.         if (!$this->tokenStorage->getToken() ||
  26.             false === $this->authorizationChecker->isGranted('ROLE_USER')
  27.         ) {
  28.             return;
  29.         }
  30.         /** @var ShopUser $shopUser */
  31.         $shopUser $this->tokenStorage->getToken()->getUser();
  32.         $this->session->set('__userId'$shopUser->getId());
  33.         CartManager::syncSessionWithRedis($this->session);
  34.     }
  35.     public function onKernelResponse(ResponseEvent $event)
  36.     {
  37.         if (!$this->tokenStorage->getToken() ||
  38.             false === $this->authorizationChecker->isGranted('ROLE_USER')
  39.         ) {
  40.             return;
  41.         }
  42.         /** @var ShopUser $shopUser */
  43.         $shopUser $this->tokenStorage->getToken()->getUser();
  44.         $this->session->set('__userId'$shopUser->getId());
  45.     }
  46. }