src/Service/Admin/Session.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\Service\Admin;
  3. use App\Entity\Section;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. class Session
  9. {
  10.     private const SESSION_KEY 'admin_section';
  11.     private SessionInterface $session;
  12.     private ?Section $section null;
  13.     public function __construct(RequestStack $requestStackEntityManagerInterface $em)
  14.     {
  15.         try {
  16.             $this->session $requestStack->getSession();
  17.             if ($this->session->has(self::SESSION_KEY)
  18.                 && $section $em->find(Section::class, $this->session->get(self::SESSION_KEY))) {
  19.                 $this->section $section;
  20.             }
  21.         } catch (SessionNotFoundException) {
  22.         }
  23.     }
  24.     public function getSection(): ?Section
  25.     {
  26.         return $this->section;
  27.     }
  28.     public function setSection(?Section $section): self
  29.     {
  30.         if (null === $section) {
  31.             $this->session->remove(self::SESSION_KEY);
  32.         } else {
  33.             if (null === $section->getId()) {
  34.                 throw new \LogicException('Entity is not a valid persisted Section');
  35.             }
  36.             $this->session->set(self::SESSION_KEY$section->getId());
  37.         }
  38.         $this->section $section;
  39.         return $this;
  40.     }
  41. }