<?php
/**
* @copyright 2020 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Jakub MedyĆski <jme@crehler.com>
* @support Crehler <support@crehler.com>
* @created 22.01.2021
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\Inspirations\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class InspirationDeleteSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $productRepository;
public function __construct(EntityRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents()
{
return [
'inspiration.deleted' => 'onInspirationDeleted'
];
}
public function onInspirationDeleted(EntityDeletedEvent $event)
{
$ids = $event->getIds();
$context = $event->getContext();
$criteria = new Criteria();
$criteria->addFilter(new EqualsAnyFilter('inspirationId', $ids));
$productsIdsToDelete = $this->productRepository->searchIds($criteria, $context);
if ($productsIdsToDelete->getTotal() === 0) return;
$keys = array_map(function ($id) {
return ['id' => $id];
}, $productsIdsToDelete->getIds());
$this->productRepository->delete($keys, $context);
}
}