<?php
namespace MLDev\OrderBundle\Service\Cart;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
final class SessionStorage implements StorageInterface
{
/**
* Session key
*/
const SESSION_KEY = 'mldev-cart-storage';
/**
* @var SessionInterface
*/
private $session;
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
if ($requestStack->getCurrentRequest()->hasSession()) {
$this->session = $requestStack->getSession();
}
}
public function read(): array
{
return $this->session->get(self::SESSION_KEY, []);
}
public function write(array $data): void
{
$this->session->set(self::SESSION_KEY, $data);
}
public function set(int $id, int $count): array
{
$storage = $this->read();
$storage[$id] = $count;
if (!$storage[$id]) {
unset($storage[$id]);
}
$this->write($storage);
return $storage;
}
public function remove(int $id): array
{
$storage = $this->read();
if ($storage[$id] ?? null) {
unset($storage[$id]);
}
$this->write($storage);
return $storage;
}
public function clear(): void
{
$this->write([]);
}
}