vendor/sylius/sylius/src/Sylius/Bundle/ApiBundle/EventListener/ApiCartBlamerListener.php line 45

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\ApiBundle\EventListener;
  12. use Sylius\Bundle\ApiBundle\Command\BlameCart;
  13. use Sylius\Bundle\ApiBundle\SectionResolver\ShopApiOrdersSubSection;
  14. use Sylius\Bundle\CoreBundle\SectionResolver\SectionProviderInterface;
  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\Messenger\MessageBusInterface;
  21. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  22. final class ApiCartBlamerListener
  23. {
  24.     private CartContextInterface $cartContext;
  25.     private SectionProviderInterface $uriBasedSectionContext;
  26.     private MessageBusInterface $commandBus;
  27.     public function __construct(
  28.         CartContextInterface $cartContext,
  29.         SectionProviderInterface $uriBasedSectionContext,
  30.         MessageBusInterface $commandBus
  31.     ) {
  32.         $this->cartContext $cartContext;
  33.         $this->uriBasedSectionContext $uriBasedSectionContext;
  34.         $this->commandBus $commandBus;
  35.     }
  36.     public function onInteractiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
  37.     {
  38.         if (!$this->uriBasedSectionContext->getSection() instanceof ShopApiOrdersSubSection) {
  39.             return;
  40.         }
  41.         $user $interactiveLoginEvent->getAuthenticationToken()->getUser();
  42.         if (!$user instanceof ShopUserInterface) {
  43.             return;
  44.         }
  45.         $cart $this->getCart();
  46.         if (null === $cart || null !== $cart->getCustomer()) {
  47.             return;
  48.         }
  49.         $this->commandBus->dispatch(new BlameCart($user->getEmail(), $cart->getTokenValue()));
  50.     }
  51.     /**
  52.      * @throws UnexpectedTypeException
  53.      */
  54.     private function getCart(): ?OrderInterface
  55.     {
  56.         try {
  57.             $cart $this->cartContext->getCart();
  58.         } catch (CartNotFoundException $exception) {
  59.             return null;
  60.         }
  61.         if (!$cart instanceof OrderInterface) {
  62.             throw new UnexpectedTypeException($cartOrderInterface::class);
  63.         }
  64.         return $cart;
  65.     }
  66. }