<?php
namespace Boab\EcommerceBundle\Storage;
use Boab\EcommerceBundle\Entity\Cart;
use Boab\EcommerceBundle\Entity\Order;
use Boab\EcommerceBundle\Entity\CartInterface;
use Boab\EcommerceBundle\Repository\CartRepository;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class CartStorage
{
/**
* The request stack.
*
* @var RequestStack
*/
private $requestStack;
/**
* The cart repository.
*
* @var OrderRepository
*/
private $cartRepository;
/**
* @var string
*/
public const CART_KEY_NAME = '__SHOPPING_CART__';
/**
* CartSessionStorage constructor.
*/
public function __construct(RequestStack $requestStack, CartRepository $cartRepository)
{
$this->requestStack = $requestStack;
$this->cartRepository = $cartRepository;
}
/**
* Gets the cart in session.
*/
public function getCart(): ?CartInterface
{
if(!$this->getCartId()){
return new Cart([]);
}
$cart = $this->cartRepository->findOneBy([
'uniqueId' => $this->getCartId(),
'status' => CartInterface::STATUS_CART,
]);
if(!$cart){
return new Cart([]);
}
return $cart;
}
/**
* Sets the cart in session.
*/
public function save(CartInterface $cart): void
{
if(!$cart->getUniqueId()){
$cart->setCreatedAt(new \DateTime('now'));
$cart->setUniqueId(bin2hex(random_bytes(20)));
$cart->setStatus(CartInterface::STATUS_CART);
}else{
$cart->setUpdatedAt(new \DateTime('now'));
}
$cart = $this->cartRepository->saveCart($cart);
$this->getSession()->set(self::CART_KEY_NAME, $cart->getUniqueId());
//$this->session->set(self::CART_KEY_NAME, serialize($cart));
}
public function emptyCart():void
{
$this->getSession()->remove(self::CART_KEY_NAME);
}
/**
* Returns the cart id.
*/
private function getCartId(): ?string
{
return $this->getSession()->get(self::CART_KEY_NAME);
}
private function getSession(): SessionInterface
{
return $this->requestStack->getSession();
}
}