src/Sylius/Bundle/CoreBundle/EventListener/CartBlamerListener.php line 49

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\CoreBundle\EventListener;
  12. use Doctrine\Common\Persistence\ObjectManager;
  13. use Sylius\Bundle\UserBundle\Event\UserEvent;
  14. use Sylius\Component\Core\Model\OrderInterface;
  15. use Sylius\Component\Core\Model\ShopUserInterface;
  16. use Sylius\Component\Order\Context\CartContextInterface;
  17. use Sylius\Component\Order\Context\CartNotFoundException;
  18. use Sylius\Component\Resource\Exception\UnexpectedTypeException;
  19. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  20. final class CartBlamerListener
  21. {
  22.     /** @var ObjectManager */
  23.     private $cartManager;
  24.     /** @var CartContextInterface */
  25.     private $cartContext;
  26.     public function __construct(ObjectManager $cartManagerCartContextInterface $cartContext)
  27.     {
  28.         $this->cartManager $cartManager;
  29.         $this->cartContext $cartContext;
  30.     }
  31.     public function onImplicitLogin(UserEvent $userEvent): void
  32.     {
  33.         $user $userEvent->getUser();
  34.         if (!$user instanceof ShopUserInterface) {
  35.             return;
  36.         }
  37.         $this->blame($user);
  38.     }
  39.     public function onInteractiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
  40.     {
  41.         $user $interactiveLoginEvent->getAuthenticationToken()->getUser();
  42.         if (!$user instanceof ShopUserInterface) {
  43.             return;
  44.         }
  45.         $this->blame($user);
  46.     }
  47.     private function blame(ShopUserInterface $user): void
  48.     {
  49.         $cart $this->getCart();
  50.         if (null === $cart) {
  51.             return;
  52.         }
  53.         $cart->setCustomer($user->getCustomer());
  54.         $this->cartManager->persist($cart);
  55.         $this->cartManager->flush();
  56.     }
  57.     /**
  58.      * @throws UnexpectedTypeException
  59.      */
  60.     private function getCart(): ?OrderInterface
  61.     {
  62.         try {
  63.             $cart $this->cartContext->getCart();
  64.         } catch (CartNotFoundException $exception) {
  65.             return null;
  66.         }
  67.         if (!$cart instanceof OrderInterface) {
  68.             throw new UnexpectedTypeException($cartOrderInterface::class);
  69.         }
  70.         return $cart;
  71.     }
  72. }