<?php
namespace Customize\EventSubscriber;
use Eccube\Entity\Customer;
use Eccube\Service\CartService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class LoginCartNormalizeSubscriber implements EventSubscriberInterface
{
/**
* @var CartService
*/
private $cartService;
public function __construct(CartService $cartService)
{
$this->cartService = $cartService;
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onLogin',
];
}
public function onLogin(InteractiveLoginEvent $event)
{
$token = $event->getAuthenticationToken();
if (!$token) {
return;
}
$user = $token->getUser();
if (!$user instanceof Customer) {
// 管理画面ログインなど、Customer 以外は対象外
return;
}
foreach ($this->cartService->getCarts() as $Cart) {
$seen = [];
$items = iterator_to_array($Cart->getCartItems());
foreach ($items as $CartItem) {
$pc = $CartItem->getProductClass();
if (!$pc) {
$Cart->removeCartItem($CartItem);
continue;
}
$pcId = $pc->getId();
if (isset($seen[$pcId])) {
$Cart->removeCartItem($CartItem);
} else {
$CartItem->setQuantity(1);
$seen[$pcId] = true;
}
}
}
$this->cartService->save();
}
}