custom/plugins/MbdusArticleSort/src/Subscriber/ProductCategory.php line 49

Open in your IDE?
  1. <?php
  2. namespace MbdusArticleSort\Subscriber;
  3. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  4. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Shopware\Core\Content\Product\ProductEvents;
  10. use MbdusArticleSort\Core\Content\Product\Extension\ProductExtension;
  11. class ProductCategory implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var EntityRepositoryInterface
  15.      */
  16.     private $productCategorySortRepository;
  17.     public function __construct(EntityRepositoryInterface $entityRepository)
  18.     {
  19.         $this->productCategorySortRepository $entityRepository;
  20.     }
  21.     public static function getSubscribedEvents()
  22.     {
  23.         return [
  24.             'product_category.written' => 'onProductCategoryWritten',
  25.             'product_category.deleted' => 'onProductCategoryDeleted'
  26.         ];
  27.     }
  28.     public function onProductCategoryDeleted(EntityDeletedEvent $event)
  29.     {
  30.         $criteria = new Criteria();
  31.         $criteria->addFilter(new EqualsFilter('productId'$event->getIds()[0]['productId']));
  32.         $criteria->addFilter(new EqualsFilter('categoryId'$event->getIds()[0]['categoryId']));
  33.         $entityToDelete $this->productCategorySortRepository->search($criteria$event->getContext());
  34.         if ($entityToDelete->getTotal() === 0) {
  35.             return;
  36.         }
  37.         $this->productCategorySortRepository->delete([['id' => $entityToDelete->getEntities()->first()->getId()]], $event->getContext());
  38.     }
  39.     public function onProductCategoryWritten(EntityWrittenEvent $event)
  40.     {
  41.         $criteria = new Criteria();
  42.         $criteria->addFilter(new EqualsFilter('categoryId'$event->getWriteResults()[0]->getPrimaryKey()['categoryId']));
  43.        
  44.         $productCategory $this->productCategorySortRepository->search($criteria$event->getContext());
  45.         if ($productCategory->getTotal() === 0) {
  46.             return;
  47.         }
  48.      
  49.         $this->productCategorySortRepository->create([[
  50.             'productId' => $event->getIds()[0]['productId'],
  51.             'categoryId' => $event->getIds()[0]['categoryId'],
  52.             'sort' => 0
  53.         ]], $event->getContext());
  54.     }
  55. }