src/Sylius/Bundle/CoreBundle/Storage/CartSessionStorage.php line 38

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\Storage;
  12. use Sylius\Bundle\CoreBundle\Provider\SessionProvider;
  13. use Sylius\Component\Core\Model\ChannelInterface;
  14. use Sylius\Component\Core\Model\OrderInterface;
  15. use Sylius\Component\Core\Repository\OrderRepositoryInterface;
  16. use Sylius\Component\Core\Storage\CartStorageInterface;
  17. use Symfony\Component\HttpFoundation\RequestStack;
  18. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  19. final class CartSessionStorage implements CartStorageInterface
  20. {
  21.     public function __construct(
  22.         private RequestStack|SessionInterface $requestStackOrSession,
  23.         private string $sessionKeyName,
  24.         private OrderRepositoryInterface $orderRepository,
  25.     ) {
  26.         if ($requestStackOrSession instanceof SessionInterface) {
  27.             trigger_deprecation('sylius/core-bundle''1.12'sprintf('Passing an instance of %s as constructor argument for %s is deprecated as of Sylius 1.12 and will be removed in 2.0. Pass an instance of %s instead.'SessionInterface::class, self::class, RequestStack::class));
  28.         }
  29.     }
  30.     public function hasForChannel(ChannelInterface $channel): bool
  31.     {
  32.         return SessionProvider::getSession($this->requestStackOrSession)->has($this->getCartKeyName($channel));
  33.     }
  34.     public function getForChannel(ChannelInterface $channel): ?OrderInterface
  35.     {
  36.         if ($this->hasForChannel($channel)) {
  37.             $cartId SessionProvider::getSession($this->requestStackOrSession)->get($this->getCartKeyName($channel));
  38.             return $this->orderRepository->findCartByChannel($cartId$channel);
  39.         }
  40.         return null;
  41.     }
  42.     public function setForChannel(ChannelInterface $channelOrderInterface $cart): void
  43.     {
  44.         SessionProvider::getSession($this->requestStackOrSession)->set($this->getCartKeyName($channel), $cart->getId());
  45.     }
  46.     public function removeForChannel(ChannelInterface $channel): void
  47.     {
  48.         SessionProvider::getSession($this->requestStackOrSession)->remove($this->getCartKeyName($channel));
  49.     }
  50.     private function getCartKeyName(ChannelInterface $channel): string
  51.     {
  52.         return sprintf('%s.%s'$this->sessionKeyName$channel->getCode());
  53.     }
  54. }