app/Customize/EventSubscriber/LoginCartNormalizeSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace Customize\EventSubscriber;
  3. use Eccube\Entity\Customer;
  4. use Eccube\Service\CartService;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\Security\Http\SecurityEvents;
  7. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  8. class LoginCartNormalizeSubscriber implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @var CartService
  12.      */
  13.     private $cartService;
  14.     public function __construct(CartService $cartService)
  15.     {
  16.         $this->cartService $cartService;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             SecurityEvents::INTERACTIVE_LOGIN => 'onLogin',
  22.         ];
  23.     }
  24.     public function onLogin(InteractiveLoginEvent $event)
  25.     {
  26.         $token $event->getAuthenticationToken();
  27.         if (!$token) {
  28.             return;
  29.         }
  30.         $user $token->getUser();
  31.         if (!$user instanceof Customer) {
  32.             // 管理画面ログインなど、Customer 以外は対象外
  33.             return;
  34.         }
  35.         foreach ($this->cartService->getCarts() as $Cart) {
  36.             $seen = [];
  37.             $items iterator_to_array($Cart->getCartItems());
  38.             foreach ($items as $CartItem) {
  39.                 $pc $CartItem->getProductClass();
  40.                 if (!$pc) {
  41.                     $Cart->removeCartItem($CartItem);
  42.                     continue;
  43.                 }
  44.                 $pcId $pc->getId();
  45.                 if (isset($seen[$pcId])) {
  46.                     $Cart->removeCartItem($CartItem);
  47.                 } else {
  48.                     $CartItem->setQuantity(1);
  49.                     $seen[$pcId] = true;
  50.                 }
  51.             }
  52.         }
  53.         $this->cartService->save();
  54.     }
  55. }