<?php
namespace App\EventSubscriber;
use App\Entity\Session;
use App\Event\SessionPostUpdateEvent;
use App\Event\SessionPostPersistEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SessionSubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $_em
) {}
public static function getSubscribedEvents(): array
{
return [
SessionPostPersistEvent::NAME => 'postPersist',
SessionPostUpdateEvent::NAME => 'postUpdate'
];
}
public function postPersist(SessionPostPersistEvent $event)
{
$data = $event->getObject();
$this->updateLastSession($data);
}
public function postUpdate(SessionPostUpdateEvent $event)
{
$data = $event->getObject();
$this->updateLastSession($data);
}
private function updateLastSession($data)
{
$lastSessionsOfTheDay = $this->_em->getRepository(Session::class)
->getLastSessionOfTheDay($data);
if (isset($lastSessionsOfTheDay[0]) && !$lastSessionsOfTheDay[0]->getIsLastOfTheDay()) {
$this->_em->getRepository(Session::class)->resetLastSessionOfTheDay($data);
$lastSessionsOfTheDay[0]->setIsLastOfTheDay(true);
$this->_em->persist($lastSessionsOfTheDay[0]);
$this->_em->flush();
}
}
}