src/EventSubscriber/InvalidateNewsCacheTagsEventSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\NewsInterface;
  5. use App\Entity\NewsTranslationInterface;
  6. use App\Extension\NewsExtension;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
  8. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  9. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Contracts\Cache\TagAwareCacheInterface;
  12. class InvalidateNewsCacheTagsEventSubscriber implements EventSubscriberInterface
  13. {
  14.     private TagAwareCacheInterface $cache;
  15.     public function __construct(TagAwareCacheInterface $cache)
  16.     {
  17.         $this->cache $cache;
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             AfterEntityPersistedEvent::class => 'onEntityPersisted',
  23.             AfterEntityUpdatedEvent::class => 'onEntityUpdated',
  24.             AfterEntityDeletedEvent::class => 'onEntityDeleted'
  25.         ];
  26.     }
  27.     public function onEntityPersisted(AfterEntityPersistedEvent $event): void
  28.     {
  29.         $this->clearCache($event);
  30.     }
  31.     public function onEntityUpdated(AfterEntityUpdatedEvent $event): void
  32.     {
  33.         $this->clearCache($event->getEntityInstance());
  34.     }
  35.     public function onEntityDeleted(AfterEntityDeletedEvent $event): void
  36.     {
  37.         $this->clearCache($event->getEntityInstance());
  38.     }
  39.     private function clearCache($entity): void
  40.     {
  41.         if ($entity instanceof NewsInterface) {
  42.             $this->clearNewsCache($entity);
  43.         } elseif ($entity instanceof NewsTranslationInterface) {
  44.             $this->clearNewsCache($entity->getNews());
  45.         }
  46.     }
  47.     private function clearNewsCache(NewsInterface $news): void
  48.     {
  49.         $this->cache->invalidateTags([sprintf('%s.%d'NewsExtension::CACHE_TAG$news->getId())]);
  50.     }
  51. }