<?php
namespace App\EventSubscriber;
use App\Entity\SessionReaction;
use Doctrine\ORM\EntityManagerInterface;
use App\Event\SessionReactionPreRemoveEvent;
use App\Event\SessionReactionPostPersistEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SessionReactionSubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $_em,
) {}
public static function getSubscribedEvents(): array
{
return [
SessionReactionPostPersistEvent::NAME => 'onPostCreate',
SessionReactionPreRemoveEvent::NAME => 'onPreRemove',
];
}
public function onPostCreate(SessionReactionPostPersistEvent $event)
{
$this->calculateCount($event, 'add');
}
public function onPreRemove(SessionReactionPreRemoveEvent $event)
{
$this->calculateCount($event, 'remove');
}
private function calculateCount($event, $type)
{
$object = $event->getObject();
$session = $object->getSession();
$totalReactions = $this->_em->getRepository(SessionReaction::class)
->getTotalReactions($session);
$session->setTotalReactions($type === 'remove' ? ($totalReactions-1) : $totalReactions);
$totalReactionsByType = $session->getTotalReactionsByType();
if (empty($totalReactionsByType)) {
$totalReactionsByType = [
SessionReaction::TYPE_THUMBSUP => 0,
SessionReaction::TYPE_CLAPS => 0,
SessionReaction::TYPE_HEART => 0
];
}
$totalReactionsByType[$object->getType()] += $type === 'remove' ? -1 : 1;
$session->setTotalReactionsByType($totalReactionsByType);
$this->_em->persist($session);
$this->_em->flush();
}
}