|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Drupal\hoeringsportal_dialogue\EventSubscriber; |
| 6 | + |
| 7 | +use Drupal\Core\Cache\CacheTagsInvalidatorInterface; |
| 8 | +use Drupal\flag\Event\FlaggingEvent; |
| 9 | +use Drupal\flag\Event\UnflaggingEvent; |
| 10 | +use Drupal\node\NodeInterface; |
| 11 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 12 | + |
| 13 | +/** |
| 14 | + * Invalidates node cache when flagged or unflagged. |
| 15 | + */ |
| 16 | +final readonly class FlagCacheInvalidationSubscriber implements EventSubscriberInterface { |
| 17 | + |
| 18 | + public function __construct( |
| 19 | + private CacheTagsInvalidatorInterface $cacheTagsInvalidator, |
| 20 | + ) {} |
| 21 | + |
| 22 | + /** |
| 23 | + * Invalidates the cache for the flagged/unflagged node. |
| 24 | + */ |
| 25 | + public function onFlagChange(FlaggingEvent|UnflaggingEvent $event): void { |
| 26 | + if ($event instanceof FlaggingEvent) { |
| 27 | + $flagging = $event->getFlagging(); |
| 28 | + $entity = $flagging->getFlaggable(); |
| 29 | + } |
| 30 | + else { |
| 31 | + $flaggings = $event->getFlaggings(); |
| 32 | + $flagging = reset($flaggings); |
| 33 | + $entity = $flagging->getFlaggable(); |
| 34 | + } |
| 35 | + |
| 36 | + if ($entity instanceof NodeInterface) { |
| 37 | + $this->cacheTagsInvalidator->invalidateTags($entity->getCacheTags()); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * {@inheritdoc} |
| 43 | + */ |
| 44 | + public static function getSubscribedEvents(): array { |
| 45 | + return [ |
| 46 | + 'flag.entity_flagged' => ['onFlagChange'], |
| 47 | + 'flag.entity_unflagged' => ['onFlagChange'], |
| 48 | + ]; |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments