<?php
namespace App\EventListener;
use App\Entity\User\ShopUser;
use App\Manager\Cart\CartManager;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class AuthenticationListener
{
private $session;
private $tokenStorage;
private $authorizationChecker;
public function __construct(SessionInterface $session,
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $authorizationChecker)
{
$this->session = $session;
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $authorizationChecker;
}
public function onAuthenticationSuccess(InteractiveLoginEvent $event)
{
if (!$this->tokenStorage->getToken() ||
false === $this->authorizationChecker->isGranted('ROLE_USER')
) {
return;
}
/** @var ShopUser $shopUser */
$shopUser = $this->tokenStorage->getToken()->getUser();
$this->session->set('__userId', $shopUser->getId());
CartManager::syncSessionWithRedis($this->session);
}
public function onKernelResponse(ResponseEvent $event)
{
if (!$this->tokenStorage->getToken() ||
false === $this->authorizationChecker->isGranted('ROLE_USER')
) {
return;
}
/** @var ShopUser $shopUser */
$shopUser = $this->tokenStorage->getToken()->getUser();
$this->session->set('__userId', $shopUser->getId());
}
}