<?php
namespace MbdusArticleSort\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
use MbdusArticleSort\Core\Content\Product\Extension\ProductExtension;
class ProductCategory implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $productCategorySortRepository;
public function __construct(EntityRepositoryInterface $entityRepository)
{
$this->productCategorySortRepository = $entityRepository;
}
public static function getSubscribedEvents()
{
return [
'product_category.written' => 'onProductCategoryWritten',
'product_category.deleted' => 'onProductCategoryDeleted'
];
}
public function onProductCategoryDeleted(EntityDeletedEvent $event)
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $event->getIds()[0]['productId']));
$criteria->addFilter(new EqualsFilter('categoryId', $event->getIds()[0]['categoryId']));
$entityToDelete = $this->productCategorySortRepository->search($criteria, $event->getContext());
if ($entityToDelete->getTotal() === 0) {
return;
}
$this->productCategorySortRepository->delete([['id' => $entityToDelete->getEntities()->first()->getId()]], $event->getContext());
}
public function onProductCategoryWritten(EntityWrittenEvent $event)
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('categoryId', $event->getWriteResults()[0]->getPrimaryKey()['categoryId']));
$productCategory = $this->productCategorySortRepository->search($criteria, $event->getContext());
if ($productCategory->getTotal() === 0) {
return;
}
$this->productCategorySortRepository->create([[
'productId' => $event->getIds()[0]['productId'],
'categoryId' => $event->getIds()[0]['categoryId'],
'sort' => 0
]], $event->getContext());
}
}