<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\NewsInterface;
use App\Entity\NewsTranslationInterface;
use App\Extension\NewsExtension;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
class InvalidateNewsCacheTagsEventSubscriber implements EventSubscriberInterface
{
private TagAwareCacheInterface $cache;
public function __construct(TagAwareCacheInterface $cache)
{
$this->cache = $cache;
}
public static function getSubscribedEvents(): array
{
return [
AfterEntityPersistedEvent::class => 'onEntityPersisted',
AfterEntityUpdatedEvent::class => 'onEntityUpdated',
AfterEntityDeletedEvent::class => 'onEntityDeleted'
];
}
public function onEntityPersisted(AfterEntityPersistedEvent $event): void
{
$this->clearCache($event);
}
public function onEntityUpdated(AfterEntityUpdatedEvent $event): void
{
$this->clearCache($event->getEntityInstance());
}
public function onEntityDeleted(AfterEntityDeletedEvent $event): void
{
$this->clearCache($event->getEntityInstance());
}
private function clearCache($entity): void
{
if ($entity instanceof NewsInterface) {
$this->clearNewsCache($entity);
} elseif ($entity instanceof NewsTranslationInterface) {
$this->clearNewsCache($entity->getNews());
}
}
private function clearNewsCache(NewsInterface $news): void
{
$this->cache->invalidateTags([sprintf('%s.%d', NewsExtension::CACHE_TAG, $news->getId())]);
}
}