<?php
namespace Lnb\Shopware6\LnbFaq\Subscriber;
use Lnb\Shopware6\LnbFaq\Content\Faq\FaqDefinition;
use Lnb\Shopware6\LnbFaq\Content\FaqGroup\FaqGroupDefinition;
use Lnb\Shopware6\LnbFaq\Content\FaqGroupPosition\FaqGroupPositionDefinition;
use Shopware\Core\Content\Category\Event\CategoryRouteCacheTagsEvent;
use Shopware\Core\Content\Category\SalesChannel\CategoryRouteResponse;
use Shopware\Core\Content\Cms\CmsPageEntity;
use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CacheInvalidationSubscriber implements EventSubscriberInterface
{
public function __construct(
private CacheInvalidator $cacheInvalidator
) {
}
public static function getSubscribedEvents(): array
{
return [
EntityWrittenContainerEvent::class => 'invalidateCache',
CategoryRouteCacheTagsEvent::class => 'invalidateCategoryCache',
];
}
public function invalidateCache(EntityWrittenContainerEvent $event): void
{
if (
!empty($event->getPrimaryKeys(FaqDefinition::ENTITY_NAME)) ||
!empty($event->getPrimaryKeys(FaqGroupDefinition::ENTITY_NAME)) ||
!empty($event->getPrimaryKeys(FaqGroupPositionDefinition::ENTITY_NAME))
) {
$this->cacheInvalidator->invalidate(
['any-faq'],
true
);
}
}
public function invalidateCategoryCache(CategoryRouteCacheTagsEvent $event): void
{
$response = $event->getResponse();
if (!$response instanceof CategoryRouteResponse) {
return;
}
$page = $response->getCategory()->getCmsPage();
if (!$page instanceof CmsPageEntity) {
return;
}
$slots = $page->getElementsOfType('lnb-faq-groups');
if (!empty($slots)) {
$event->setTags(
array_merge($event->getTags(), ['any-faq'])
);
}
}
}