src/Sylius/Bundle/ShopBundle/EventListener/SessionCartSubscriber.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\ShopBundle\EventListener;
  12. use Sylius\Component\Core\Model\OrderInterface;
  13. use Sylius\Component\Core\Storage\CartStorageInterface;
  14. use Sylius\Component\Order\Context\CartContextInterface;
  15. use Sylius\Component\Order\Context\CartNotFoundException;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. use Webmozart\Assert\Assert;
  20. final class SessionCartSubscriber implements EventSubscriberInterface
  21. {
  22.     /** @var CartContextInterface */
  23.     private $cartContext;
  24.     /** @var CartStorageInterface */
  25.     private $cartStorage;
  26.     public function __construct(CartContextInterface $cartContextCartStorageInterface $cartStorage)
  27.     {
  28.         $this->cartContext $cartContext;
  29.         $this->cartStorage $cartStorage;
  30.     }
  31.     /**
  32.      * {@inheritdoc}
  33.      */
  34.     public static function getSubscribedEvents(): array
  35.     {
  36.         return [
  37.             KernelEvents::RESPONSE => ['onKernelResponse'],
  38.         ];
  39.     }
  40.     public function onKernelResponse(FilterResponseEvent $event): void
  41.     {
  42.         if (!$event->isMasterRequest()) {
  43.             return;
  44.         }
  45.         $session $event->getRequest()->getSession();
  46.         if ($session && !$session->isStarted()) {
  47.             return;
  48.         }
  49.         try {
  50.             /** @var OrderInterface $cart */
  51.             $cart $this->cartContext->getCart();
  52.             Assert::isInstanceOf($cartOrderInterface::class);
  53.         } catch (CartNotFoundException $exception) {
  54.             return;
  55.         }
  56.         if (null !== $cart && null !== $cart->getId() && null !== $cart->getChannel()) {
  57.             $this->cartStorage->setForChannel($cart->getChannel(), $cart);
  58.         }
  59.     }
  60. }