<?php
namespace App\Event;
use App\Component\Cart\CartFactory;
use App\Component\Cart\Storage\CartSessionStorage;
use App\Component\CartService;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
class UserInteractiveLoginSubscriber implements EventSubscriberInterface
{
private $em;
private $session;
private $cartService;
private $logger;
public function __construct(EntityManagerInterface $em, SessionInterface $session, CartService $cartService, LoggerInterface $logger)
{
$this->em = $em;
$this->session = $session;
$this->cartService = $cartService;
$this->logger = $logger;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
if (get_class($user) == User::class) {
$this->logger->debug('onSecurityInteractiveLogin');
// カート追加時はカートに商品を追加
$beforeLoginParams = $this->session->get('auth_adding_item');
// dd($this->session->all());
if (is_array($beforeLoginParams)) {
$this->logger->debug('before login params ');
if (array_key_exists('menuId', $beforeLoginParams)) {
$this->logger->debug('menuId exists');
// 商品指定があるのでカートに追加
$menu = $this->em->getRepository('App:Menu')->find($beforeLoginParams['menuId']);
if ($menu) {
$this->logger->debug('menu exists');
$quantity = 1;
if (array_key_exists('quantity', $beforeLoginParams)) {
// 数量指定があれば適用
$quantity = $beforeLoginParams['quantity'];
}
// アイテムをカートに追加
$this->cartService->addCartItem($user, $menu, $quantity);
// dd($this->cartFactory->getCurrent());
$this->logger->debug('added item');
}
}
}
// $user->setLastLoginAt(new \DateTime());
// $this->em->persist($user);
$this->em->flush();
}
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
}