src/Storage/CartSessionStorage.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\Storage;
  3. use App\Entity\Order;
  4. use App\Repository\OrderRepository;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. class CartSessionStorage
  8. {
  9. private RequestStack $requestStack;
  10. private OrderRepository $cartRepository;
  11. /**
  12. * @var string
  13. */
  14. public const CART_KEY_NAME = 'cart_id';
  15. /**
  16. * CartSessionStorage constructor.
  17. */
  18. public function __construct(RequestStack $requestStack, OrderRepository $cartRepository)
  19. {
  20. $this->requestStack = $requestStack;
  21. $this->cartRepository = $cartRepository;
  22. }
  23. /**
  24. * Gets the cart in session.
  25. */
  26. public function getCart(): ?Order
  27. {
  28. return $this->cartRepository->findOneBy([
  29. 'id' => $this->getCartId(),
  30. 'status' => Order::STATUS_CART,
  31. ]);
  32. }
  33. /**
  34. * Sets the cart in session.
  35. */
  36. public function setCart(Order $cart): void
  37. {
  38. $this->getSession()->set(self::CART_KEY_NAME, $cart->getId());
  39. }
  40. public function clearCart()
  41. {
  42. $this->getSession()->remove(self::CART_KEY_NAME);
  43. }
  44. /**
  45. * Returns the cart id.
  46. */
  47. private function getCartId(): ?int
  48. {
  49. return $this->getSession()->get(self::CART_KEY_NAME);
  50. }
  51. private function getSession(): SessionInterface
  52. {
  53. return $this->requestStack->getSession();
  54. }
  55. }