<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use MLDev\AccountBundle\Entity\Account;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
/**
* Class FavouritesStorage
* @package App\Services
*/
class FavouritesStorage
{
const STORAGE_KEY = 'mldev-favourites-storage';
/**
* @var SessionInterface
*/
private $session;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var Security
*/
private $security;
/**
* FavouritesStorage constructor.
*/
public function __construct(Security $security, RequestStack $requestStack, EntityManagerInterface $entityManager)
{
$this->session = $requestStack->getSession();
$this->security = $security;
$this->entityManager = $entityManager;
}
/**
* Read data from session
*/
public function read(): array
{
$user = $this->security->getUser();
$favourites = [];
if ($user instanceof Account) {
$favourites = $user->getFavourites();
}
$this->session->set(self::STORAGE_KEY, $favourites);
return $favourites;
}
/**
* Write data in session
*/
public function write(array $data = []): void
{
$user = $this->security->getUser();
if ($user instanceof Account) {
$user->setFavourites($data);
}
$this->session->set(self::STORAGE_KEY, $data);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
/**
* 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();
}
}