custom/plugins/WbfkExpertRating/src/Subscriber/ExpertRatingEntitySubscriber.php line 40

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Wbfk\ExpertRating\Subscriber;
  4. use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class ExpertRatingEntitySubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         private readonly EntityRepository $expertRatingRepository,
  15.         private readonly EntityRepository $expertRatingPropertyRepository,
  16.         private readonly CacheInvalidator $cacheInvalidator
  17.     ) {
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             'wbfk_expert_rating.written' => 'wbfkExpertRatingWritten',
  23.             'wbfk_expert_rating.deleted' => 'wbfkExpertRatingWritten',
  24.             'wbfk_expert_rating_property.written' => 'wbfkExpertRatingPropertyWritten',
  25.             'wbfk_expert_rating_property.deleted' => 'wbfkExpertRatingPropertyWritten',
  26.         ];
  27.     }
  28.     public function wbfkExpertRatingWritten(EntityWrittenEvent $event): void
  29.     {
  30.         $this->clearProductCacheByExpertRatingIds($event->getIds(), $event->getContext());
  31.     }
  32.     public function wbfkExpertRatingPropertyWritten(EntityWrittenEvent $event): void
  33.     {
  34.         $expertRatingPropertySearchResult $this->expertRatingPropertyRepository->search((new Criteria($event->getIds())), $event->getContext());
  35.         $expertRatingProperty $expertRatingPropertySearchResult->first();
  36.         $this->clearProductCacheByExpertRatingIds([$expertRatingProperty->getExpertRatingId()], $event->getContext());
  37.     }
  38.     private function clearProductCacheByExpertRatingIds(array $idsContext $context): void
  39.     {
  40.         $expertRatingSearchResult $this->expertRatingRepository->search((new Criteria($ids))->addAssociation('expertRatingExtensions'), $context);
  41.         $expertRating $expertRatingSearchResult->first();
  42.         $productIds = [];
  43.         foreach ($expertRating->getExpertRatingExtensions() as $product) {
  44.             $productIds[] = $product->__get('productId');
  45.         }
  46.         if (!empty($productIds)) {
  47.             $this->cacheInvalidator->invalidate(
  48.                 array_map([EntityCacheKeyGenerator::class, 'buildProductTag'], $productIds)
  49.             );
  50.         }
  51.     }
  52. }