<?php
namespace Wbfk\CmsHideParts\Cache;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Shopware\Core\Content\Category\SalesChannel\CachedCategoryRoute;
use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Wbfk\CmsHideParts\DataAbstractionLayer\HiddenCmsPartsDefinition;
use Wbfk\CmsHideParts\DataAbstractionLayer\HiddenEntityPartsDefinition;
class CacheInvalidationSubscriber implements EventSubscriberInterface
{
/**
* @var CacheInvalidator
*/
private CacheInvalidator $cacheInvalidator;
/**
* @var Connection
*/
private Connection $connection;
public function __construct(CacheInvalidator $cacheInvalidator, Connection $connection)
{
$this->cacheInvalidator = $cacheInvalidator;
$this->connection = $connection;
}
/**
* @return \array[][]
*/
public static function getSubscribedEvents(): array
{
return [
EntityWrittenContainerEvent::class => [
['invalidatePage', 3001],
]
];
}
/**
* @throws Exception
*/
public function invalidatePage(EntityWrittenContainerEvent $event): void
{
$pageHiddenPartsIds = $event->getPrimaryKeys(HiddenCmsPartsDefinition::ENTITY_NAME);
if ($pageHiddenPartsIds) {
$pageIdsToInvalidate = $this->connection->fetchFirstColumn(
'SELECT LOWER(HEX(`cms_page_id`)) FROM `wbfk_hidden_cms_parts` WHERE `id` IN (:ids)',
['ids' => Uuid::fromHexToBytesList($pageHiddenPartsIds)],
['ids' => Connection::PARAM_STR_ARRAY]
);
if ($pageIdsToInvalidate) {
$this->cacheInvalidator->invalidate(
array_map([EntityCacheKeyGenerator::class, 'buildCmsTag'], $pageIdsToInvalidate)
);
}
}
$entityHiddenPartsIds = $event->getPrimaryKeys(HiddenEntityPartsDefinition::ENTITY_NAME);
if ($entityHiddenPartsIds) {
$entitiesToInvalidate = $this->connection->fetchAllAssociative(
'SELECT LOWER(HEX(`id`)) as `id`, entity, LOWER(HEX(`entity_id`)) as `entity_id` FROM `wbfk_hidden_entity_parts` WHERE `id` IN (:ids)',
['ids' => Uuid::fromHexToBytesList($entityHiddenPartsIds)],
['ids' => Connection::PARAM_STR_ARRAY]
);
$idsByType = [];
foreach ($entitiesToInvalidate as $entity) {
$idsByType[$entity['entity']][] = $entity['id'];
}
if (array_key_exists('category', $idsByType)) {
$this->cacheInvalidator->invalidate(
array_map([CachedCategoryRoute::class, 'buildName'], $idsByType['category'])
);
}
if (array_key_exists('product', $idsByType)) {
$this->cacheInvalidator->invalidate(
array_map([EntityCacheKeyGenerator::class, 'buildProductTag'], $idsByType['product'])
);
}
}
}
}