<?php
namespace App\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use App\Event\SessionQuestionPreRemoveEvent;
use App\Event\SessionQuestionPrePersistEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SessionQuestionSubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $_em,
) {}
public static function getSubscribedEvents(): array
{
return [
SessionQuestionPrePersistEvent::NAME => 'preCreate',
SessionQuestionPreRemoveEvent::NAME => 'preRemove',
];
}
public function preCreate(SessionQuestionPrePersistEvent $event)
{
$object = $event->getObject();
$session = $object->getSession();
if ($session && !$session->getIsCommentModerated()) {
$parent = $object->getParent();
if (!empty($parent)) {
$parent->setIsReplyed(true);
$this->_em->persist($parent);
}
}
}
public function preRemove(SessionQuestionPreRemoveEvent $event)
{
$object = $event->getObject();
$session = $object->getSession();
if ($session && !$session->getIsCommentModerated()) {
$parent = $object->getParent();
if (!empty($parent)) {
$children = $parent->getChildren();
if (count($children) === 1) {
$parent->setIsReplyed(false);
$this->_em->persist($parent);
}
}
}
}
}