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

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\Cart\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.     public function __construct(
  25.         private CartContextInterface $cartContext,
  26.         private SectionProviderInterface $uriBasedSectionContext,
  27.         private MessageBusInterface $commandBus,
  28.     ) {
  29.     }
  30.     public function onInteractiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
  31.     {
  32.         if (!$this->uriBasedSectionContext->getSection() instanceof ShopApiOrdersSubSection) {
  33.             return;
  34.         }
  35.         $user $interactiveLoginEvent->getAuthenticationToken()->getUser();
  36.         if (!$user instanceof ShopUserInterface) {
  37.             return;
  38.         }
  39.         $cart $this->getCart();
  40.         if (null === $cart || !$cart->isCreatedByGuest()) {
  41.             return;
  42.         }
  43.         $this->commandBus->dispatch(new BlameCart($user->getEmail(), $cart->getTokenValue()));
  44.     }
  45.     /**
  46.      * @throws UnexpectedTypeException
  47.      */
  48.     private function getCart(): ?OrderInterface
  49.     {
  50.         try {
  51.             $cart $this->cartContext->getCart();
  52.         } catch (CartNotFoundException) {
  53.             return null;
  54.         }
  55.         if (!$cart instanceof OrderInterface) {
  56.             throw new UnexpectedTypeException($cartOrderInterface::class);
  57.         }
  58.         return $cart;
  59.     }
  60. }