src/EventSubscriber/SessionSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Session;
  4. use App\Event\SessionPostUpdateEvent;
  5. use App\Event\SessionPostPersistEvent;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class SessionSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(
  11.         private EntityManagerInterface $_em
  12.     ) {}
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         return [
  16.             SessionPostPersistEvent::NAME => 'postPersist',
  17.             SessionPostUpdateEvent::NAME => 'postUpdate'
  18.         ];
  19.     }
  20.     public function postPersist(SessionPostPersistEvent $event)
  21.     {
  22.         $data $event->getObject();
  23.         $this->updateLastSession($data);
  24.     }
  25.     public function postUpdate(SessionPostUpdateEvent $event)
  26.     {
  27.         $data $event->getObject();
  28.         $this->updateLastSession($data);
  29.     }
  30.     private function updateLastSession($data)
  31.     {
  32.         $lastSessionsOfTheDay $this->_em->getRepository(Session::class)
  33.             ->getLastSessionOfTheDay($data);
  34.         if (isset($lastSessionsOfTheDay[0]) && !$lastSessionsOfTheDay[0]->getIsLastOfTheDay()) {
  35.             $this->_em->getRepository(Session::class)->resetLastSessionOfTheDay($data);
  36.             $lastSessionsOfTheDay[0]->setIsLastOfTheDay(true);
  37.             $this->_em->persist($lastSessionsOfTheDay[0]);
  38.             $this->_em->flush();
  39.         }
  40.     }
  41. }