vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/EventListener/ShopCartBlamerListener.php line 46

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\ShopBundle\EventListener;
  12. use Sylius\Bundle\CoreBundle\SectionResolver\SectionProviderInterface;
  13. use Sylius\Bundle\ShopBundle\SectionResolver\ShopSection;
  14. use Sylius\Bundle\UserBundle\Event\UserEvent;
  15. use Sylius\Component\Core\Model\OrderInterface;
  16. use Sylius\Component\Core\Model\ShopUserInterface;
  17. use Sylius\Component\Order\Context\CartContextInterface;
  18. use Sylius\Component\Order\Context\CartNotFoundException;
  19. use Sylius\Component\Resource\Exception\UnexpectedTypeException;
  20. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  21. final class ShopCartBlamerListener
  22. {
  23.     public function __construct(private CartContextInterface $cartContext, private SectionProviderInterface $uriBasedSectionContext)
  24.     {
  25.     }
  26.     public function onImplicitLogin(UserEvent $userEvent): void
  27.     {
  28.         if (!$this->uriBasedSectionContext->getSection() instanceof ShopSection) {
  29.             return;
  30.         }
  31.         $user $userEvent->getUser();
  32.         if (!$user instanceof ShopUserInterface) {
  33.             return;
  34.         }
  35.         $this->blame($user);
  36.     }
  37.     public function onInteractiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
  38.     {
  39.         $section $this->uriBasedSectionContext->getSection();
  40.         if (!$section instanceof ShopSection) {
  41.             return;
  42.         }
  43.         $user $interactiveLoginEvent->getAuthenticationToken()->getUser();
  44.         if (!$user instanceof ShopUserInterface) {
  45.             return;
  46.         }
  47.         $this->blame($user);
  48.     }
  49.     private function blame(ShopUserInterface $user): void
  50.     {
  51.         $cart $this->getCart();
  52.         if (null === $cart || null !== $cart->getCustomer()) {
  53.             return;
  54.         }
  55.         $cart->setCustomerWithAuthorization($user->getCustomer());
  56.     }
  57.     /**
  58.      * @throws UnexpectedTypeException
  59.      */
  60.     private function getCart(): ?OrderInterface
  61.     {
  62.         try {
  63.             $cart $this->cartContext->getCart();
  64.         } catch (CartNotFoundException) {
  65.             return null;
  66.         }
  67.         if (!$cart instanceof OrderInterface) {
  68.             throw new UnexpectedTypeException($cartOrderInterface::class);
  69.         }
  70.         return $cart;
  71.     }
  72. }