<?php
namespace MbdusArticleSort\Subscriber;
use MbdusArticleSort\Product\ProductCategoryiesSortDefinition;
use Shopware\Core\Content\Category\CategoryDefinition;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SortWritten implements EventSubscriberInterface
{
/**
* @var ProductCategoryDefinition
*/
private $categoryProductSortRepository;
/**
* @var CacheClearer
*/
private $cacheClearer;
/**
* @var EntityCacheKeyGenerator
*/
private $cacheKeyGenerator;
public function __construct(
EntityRepositoryInterface $categoryProductSort
)
{
$this->categoryProductSortRepository = $categoryProductSort;
}
public static function getSubscribedEvents()
{
return [
'mbdus_productcategoriessort.written' => 'entityWritten'
];
}
public function entityWritten(EntityWrittenEvent $entityWrittenEvent)
{
if (empty($entityWrittenEvent->getWriteResults())) {
return;
}
$entityWriteResult = $entityWrittenEvent->getWriteResults()[0];
if ($entityWriteResult->getOperation() !== 'update') {
// return;
}
$sortId = $entityWriteResult->getPayload()['id'];
$criteria = new Criteria([$sortId]);
$criteria->addAssociation('category');
$criteria->addAssociation('product');
$categoryProductSort = $this->categoryProductSortRepository->search($criteria, $entityWrittenEvent->getContext())->first();
$categoryId = $categoryProductSort->get('category')->getId();
$productId = $categoryProductSort->get('product')->getId();
// $this->invalidateCategoryEntityCache($categoryId);
// $this->invalidateProductEntityCache($productId);
}
private function invalidateCategoryEntityCache($categoryId)
{
$tags = [CategoryDefinition::ENTITY_NAME . '.id'];
$tags[] = $this->cacheKeyGenerator->getEntityTag($categoryId, CategoryDefinition::ENTITY_NAME);
$this->cacheClearer->invalidateTags($tags);
}
private function invalidateProductEntityCache($productId)
{
$tags[] = $this->cacheKeyGenerator->getEntityTag($productId, ProductDefinition::ENTITY_NAME);
$this->cacheClearer->invalidateTags($tags);
}
}