<?php declare(strict_types=1);
namespace NetzpEvents6\Controller\StoreApi;
use NetzpEvents6\Controller\StoreApi\EventListing\CachedEventListingRoute;
use NetzpEvents6\Core\Content\Event\EventDefinition;
use Shopware\Core\Content\Cms\Aggregate\CmsSlotTranslation\CmsSlotTranslationDefinition;
use Shopware\Core\Content\Product\SalesChannel\Detail\CachedProductDetailRoute;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
class CacheInvalidationSubscriber implements EventSubscriberInterface
{
private CacheInvalidator $cacheInvalidator;
private $eventsRepository;
private $cmsSlotsRepository;
public function __construct(CacheInvalidator $cacheInvalidator,
EntityRepository $eventsRepository,
EntityRepository $cmsSlotsRepository)
{
$this->cacheInvalidator = $cacheInvalidator;
$this->eventsRepository = $eventsRepository;
$this->cmsSlotsRepository = $cmsSlotsRepository;
}
public static function getSubscribedEvents()
{
return [
EntityWrittenContainerEvent::class => [
['invalidate', 2001]
],
];
}
public function invalidate(EntityWrittenContainerEvent $event): void
{
$changes = $event->getPrimaryKeys(EventDefinition::ENTITY_NAME);
$changesCmsSlots = $event->getPrimaryKeys(CmsSlotTranslationDefinition::ENTITY_NAME);
$changesNavigation = $event->getPrimaryKeys('category');
$mustInvalidateEventListing = false;
if (! empty($changes)) {
$criteria = new Criteria($changes);
$events = $this->eventsRepository->search($criteria, $event->getContext())->getEntities();
foreach ($events as $event) {
$productId = $event->getProductid();
if ($productId) {
$this->cacheInvalidator->invalidate([
CachedProductDetailRoute::buildName($productId)
]);
}
}
$mustInvalidateEventListing = true;
}
if ( ! empty($changesNavigation)) {
$eventListingRoutes = [];
foreach ($changesNavigation as $navigationId) {
$eventListingRoutes[] = CachedEventListingRoute::buildName($navigationId);
}
$this->cacheInvalidator->invalidate($eventListingRoutes);
}
if( ! empty($changesCmsSlots)) {
$cmsSlotIds = array_map(function($item) {
if(is_array($item) && array_key_exists('cmsSlotId', $item)) {
return $item['cmsSlotId'];
}
return $item;
}, $changesCmsSlots);
if( ! empty($cmsSlotIds)) {
$criteriaSlots = new Criteria($cmsSlotIds);
$slots = $this->cmsSlotsRepository->search($criteriaSlots, $event->getContext())->getEntities();
foreach($slots as $slot) {
if($slot->getType() == 'netzp-events6') {
$mustInvalidateEventListing = true;
break;
}
}
}
}
if($mustInvalidateEventListing) {
$this->cacheInvalidator->invalidate([
CachedEventListingRoute::buildName('')
]);
}
}
}