<?php
namespace MLDev\OrderBundle\Service;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Class CartStorage
* @package MLDev\OrderBundle\Service
*/
class CartStorage
{
/**
*
*/
const STORAGE_KEY = 'mldev-cart-storage';
/**
* @var SessionInterface
*/
private $session;
/**
* @var RequestStack
*/
private $requestStack;
/**
* Cart constructor.
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* Read data from session
*/
public function read(): array
{
return $this->getSession()->get(self::STORAGE_KEY, []);
}
/**
* Write data in session
*/
public function write(array $data = []): void
{
$this->getSession()->set(self::STORAGE_KEY, $data);
}
/**
* Set element by id and count
*/
public function set(int $id, int $count): array
{
$storage = $this->read();
// set item and count to storage
$storage[$id] = $count;
//check and remove
if (!$storage[$id]) {
// remove item from storage
unset($storage[$id]);
}
$this->write($storage);
return $storage;
}
/**
* Remove element by id
*/
public function remove(int $id): array
{
$storage = $this->read();
//check and remove
if ($storage[$id]) {
// remove item from storage
unset($storage[$id]);
}
$this->write($storage);
return $storage;
}
/**
* Clear session storage
*/
public function clear(): void
{
$this->write();
}
private function getSession()
{
if (!$this->session) {
$this->session = $this->requestStack->getSession();
}
return $this->session;
}
}