<?php
declare(strict_types=1);
namespace Wbfk\ExpertRating\Subscriber;
use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ExpertRatingEntitySubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly EntityRepository $expertRatingRepository,
private readonly EntityRepository $expertRatingPropertyRepository,
private readonly CacheInvalidator $cacheInvalidator
) {
}
public static function getSubscribedEvents(): array
{
return [
'wbfk_expert_rating.written' => 'wbfkExpertRatingWritten',
'wbfk_expert_rating.deleted' => 'wbfkExpertRatingWritten',
'wbfk_expert_rating_property.written' => 'wbfkExpertRatingPropertyWritten',
'wbfk_expert_rating_property.deleted' => 'wbfkExpertRatingPropertyWritten',
];
}
public function wbfkExpertRatingWritten(EntityWrittenEvent $event): void
{
$this->clearProductCacheByExpertRatingIds($event->getIds(), $event->getContext());
}
public function wbfkExpertRatingPropertyWritten(EntityWrittenEvent $event): void
{
$expertRatingPropertySearchResult = $this->expertRatingPropertyRepository->search((new Criteria($event->getIds())), $event->getContext());
$expertRatingProperty = $expertRatingPropertySearchResult->first();
$this->clearProductCacheByExpertRatingIds([$expertRatingProperty->getExpertRatingId()], $event->getContext());
}
private function clearProductCacheByExpertRatingIds(array $ids, Context $context): void
{
$expertRatingSearchResult = $this->expertRatingRepository->search((new Criteria($ids))->addAssociation('expertRatingExtensions'), $context);
$expertRating = $expertRatingSearchResult->first();
$productIds = [];
foreach ($expertRating->getExpertRatingExtensions() as $product) {
$productIds[] = $product->__get('productId');
}
if (!empty($productIds)) {
$this->cacheInvalidator->invalidate(
array_map([EntityCacheKeyGenerator::class, 'buildProductTag'], $productIds)
);
}
}
}