<?php
declare(strict_types=1);
namespace Swag\EnterpriseSearch\Cache;
use Psr\Cache\CacheItemPoolInterface;
use Swag\EnterpriseSearch\Action\ActionSearchTerm\Events\ActionSearchTermIndexerEvent;
use Swag\EnterpriseSearch\Action\Events\ActionIndexerEvent;
use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CacheInvalidationSubscriber implements EventSubscriberInterface
{
/**
* @var CacheItemPoolInterface[]
*/
private $adapters;
/**
* @var \Shopware\Core\Framework\Adapter\Cache\CacheInvalidator|null
*/
private $cacheInvalidator;
/**
* @param \Shopware\Core\Framework\Adapter\Cache\CacheInvalidator|null $cacheInvalidator
*/
public function __construct(array $adapters, $cacheInvalidator)
{
$this->adapters = $adapters;
$this->cacheInvalidator = $cacheInvalidator;
}
/**
* @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
*/
public static function getSubscribedEvents()
{
return [
ActionIndexerEvent::class => [
['invalidateSearch', 2000],
],
ActionSearchTermIndexerEvent::class => [
['invalidateSearch', 2000],
],
];
}
// invalidates the search and suggest route each time a term changed
public function invalidateSearch(): void
{
$tags = [
'product-suggest-route',
'product-search-route',
];
if ($this->cacheInvalidator === null) {
$this->invalidateCache($tags);
return;
}
$this->cacheInvalidator->invalidate($tags);
}
private function invalidateCache(array $keys): void
{
foreach ($this->adapters as $adapter) {
if ($adapter instanceof TagAwareAdapterInterface) {
$adapter->invalidateTags($keys);
}
}
foreach ($this->adapters as $adapter) {
$adapter->deleteItems($keys);
}
}
}