<?php declare(strict_types=1);
namespace DvdwDirectory\Content\Product\Subscriber;
use DvdwDirectory\Content\Product\SalesChannel\CachedProductCountRoute;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CacheInvalidationSubscriber implements EventSubscriberInterface
{
private CacheInvalidator $cacheInvalidator;
public function __construct(
CacheInvalidator $cacheInvalidator
)
{
$this->cacheInvalidator = $cacheInvalidator;
}
public static function getSubscribedEvents(): iterable
{
return [
ProductEvents::PRODUCT_WRITTEN_EVENT => 'invalidate',
ProductEvents::PRODUCT_DELETED_EVENT => 'invalidate'
];
}
public function invalidate(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $writeResult) {
$operation = $writeResult->getOperation();
if ($operation === EntityWriteResult::OPERATION_INSERT || $operation === EntityWriteResult::OPERATION_DELETE) {
$this->cacheInvalidator->invalidate([CachedProductCountRoute::ALL_TAG]);
break;
}
}
}
}