<?php
namespace App\Service\Admin;
use App\Entity\Section;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class Session
{
private const SESSION_KEY = 'admin_section';
private SessionInterface $session;
private ?Section $section = null;
public function __construct(RequestStack $requestStack, EntityManagerInterface $em)
{
try {
$this->session = $requestStack->getSession();
if ($this->session->has(self::SESSION_KEY)
&& $section = $em->find(Section::class, $this->session->get(self::SESSION_KEY))) {
$this->section = $section;
}
} catch (SessionNotFoundException) {
}
}
public function getSection(): ?Section
{
return $this->section;
}
public function setSection(?Section $section): self
{
if (null === $section) {
$this->session->remove(self::SESSION_KEY);
} else {
if (null === $section->getId()) {
throw new \LogicException('Entity is not a valid persisted Section');
}
$this->session->set(self::SESSION_KEY, $section->getId());
}
$this->section = $section;
return $this;
}
}