<?php declare(strict_types=1);
namespace Pixel\LexikonSW6\Controller\StoreApi;
use Pixel\LexikonSW6\Controller\StoreApi\LexikonCategories\CachedLexikonCatRoute;
use Pixel\LexikonSW6\Entities\Categories\LexikonCategoriesDefinition;
use Shopware\Core\Content\Cms\Aggregate\CmsSlotTranslation\CmsSlotTranslationDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
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 $cmsRepository;
public function __construct(CacheInvalidator $cacheInvalidator, EntityRepositoryInterface $cmsRepository)
{
$this->cacheInvalidator = $cacheInvalidator;
$this->cmsRepository = $cmsRepository;
}
public static function getSubscribedEvents()
{
// docs : https://developer.shopware.com/docs/guides/plugins/plugins/framework/store-api/add-caching-for-store-api-route
// The EntityWrittenContainerEvent is a generic event that is always thrown when an entities are written. This contains all changed entities
return [
EntityWrittenContainerEvent::class => [
['invalidate', 2001]
]
];
}
public function invalidate(EntityWrittenContainerEvent $event): void
{
// check if cagegory written.
$changesCategory = $event->getPrimaryKeys('category');
// check if own entity written. In some cases you want to use the primary keys for further cache invalidation
$changesLexikonCats = $event->getPrimaryKeys(LexikonCategoriesDefinition::ENTITY_NAME);
// check if cms slots written.
$changesCmsData = $event->getPrimaryKeys(CmsSlotTranslationDefinition::ENTITY_NAME);
$InvalidateLexikon = false;
if (!empty($changesCategory)) {
$LexikonRoutes = [];
foreach ($changesCategory as $catsId) {
$LexikonRoutes[] = CachedLexikonCatRoute::buildName($catsId);
}
$this->cacheInvalidator->invalidate($LexikonRoutes);
}
if (!empty($changesLexikonCats)) {
$LexikonDataRoutes = [];
foreach ($changesLexikonCats as $catId) {
$LexikonDataRoutes[] = CachedLexikonCatRoute::buildName($catId);
}
$this->cacheInvalidator->invalidate($LexikonDataRoutes);
$InvalidateLexikon = true;
}
if (!empty($changesCmsData)) {
$cmsSlotsIds = array_map(function ($cmsitem) {
if (is_array($cmsitem) && array_key_exists('cmsSlotId', $cmsitem)) {
return $cmsitem['cmsSlotId'];
}
return $cmsitem;
}, $changesCmsData);
if (!empty($cmsSlotsIds)) {
$criteriaCms = new Criteria($cmsSlotsIds);
$slots = $this->cmsRepository->search($criteriaCms, $event->getContext())->getEntities();
foreach ($slots as $slot) {
if ($slot->getType() == 'lexikon-categories') {
$InvalidateLexikon = true;
break;
}
}
}
}
if ($InvalidateLexikon) {
$this->cacheInvalidator->invalidate([
CachedLexikonCatRoute::buildName('')
]);
}
}
}