<?php
namespace App\EventSubscriber;
use App\Entity\VideoGalleryHistory;
use Doctrine\ORM\EntityManagerInterface;
use App\Event\VideoGalleryHistoryPreRemoveEvent;
use App\Event\VideoGalleryHistoryPostPersistEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class VideoGalleryHistorySubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $_em
) {}
public static function getSubscribedEvents(): array
{
return [
VideoGalleryHistoryPostPersistEvent::NAME => 'onPostCreate',
VideoGalleryHistoryPreRemoveEvent::NAME => 'onPreRemove'
];
}
public function onPostCreate(VideoGalleryHistoryPostPersistEvent $event)
{
$object = $event->getObject();
$videoGallery = $object->getVideoGallery();
$totalViews = $this->_em->getRepository(VideoGalleryHistory::class)->getTotalViews($videoGallery);
$videoGallery->setTotalViews($totalViews);
$this->_em->persist($videoGallery);
$this->_em->flush();
}
public function onPreRemove(VideoGalleryHistoryPreRemoveEvent $event)
{
$object = $event->getObject();
$videoGallery = $object->getVideoGallery();
$totalViews = $this->_em->getRepository(VideoGalleryHistory::class)->getTotalViews($videoGallery, $object->getId());
$videoGallery->setTotalViews($totalViews);
$this->_em->persist($videoGallery);
$this->_em->flush();
}
}