src/EventSubscriber/SessionReactionSubscriber.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\SessionReaction;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use App\Event\SessionReactionPreRemoveEvent;
  6. use App\Event\SessionReactionPostPersistEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class SessionReactionSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(
  11.         private EntityManagerInterface $_em,
  12.     ) {}
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         return [
  16.             SessionReactionPostPersistEvent::NAME => 'onPostCreate',
  17.             SessionReactionPreRemoveEvent::NAME => 'onPreRemove',
  18.         ];
  19.     }
  20.     public function onPostCreate(SessionReactionPostPersistEvent $event)
  21.     {
  22.         $this->calculateCount($event'add');
  23.     }
  24.     public function onPreRemove(SessionReactionPreRemoveEvent $event)
  25.     {
  26.         $this->calculateCount($event'remove');
  27.     }
  28.     private function calculateCount($event$type)
  29.     {
  30.         $object $event->getObject();
  31.         $session $object->getSession();
  32.         $totalReactions $this->_em->getRepository(SessionReaction::class)
  33.             ->getTotalReactions($session);
  34.         $session->setTotalReactions($type === 'remove' ? ($totalReactions-1) : $totalReactions);
  35.         $totalReactionsByType $session->getTotalReactionsByType();
  36.         if (empty($totalReactionsByType)) {
  37.             $totalReactionsByType = [
  38.                 SessionReaction::TYPE_THUMBSUP => 0,
  39.                 SessionReaction::TYPE_CLAPS => 0,
  40.                 SessionReaction::TYPE_HEART => 0
  41.             ];
  42.         }
  43.         $totalReactionsByType[$object->getType()] += $type === 'remove' ? -1;
  44.         $session->setTotalReactionsByType($totalReactionsByType);
  45.         
  46.         $this->_em->persist($session);
  47.         $this->_em->flush();
  48.     }
  49. }