<?php
declare(strict_types=1);
namespace BartCPreemiumArticle\PremiumArticle\Subscriber;
use BartCPreemiumArticle\PremiumArticle\Core\Content\Premium\PremiumEntity;
use BartCPreemiumArticle\PremiumArticle\Repository\PremiumArticleRepositoryInterface;
use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NotFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
// todo change name to checkSearchResultPage or something like that
class RemoveFromSearch implements EventSubscriberInterface
{
private PremiumArticleRepositoryInterface $getAllPreemiumWithoutSell;
public function __construct(PremiumArticleRepositoryInterface $getAllPreemiumWithoutSell)
{
$this->getAllPreemiumWithoutSell = $getAllPreemiumWithoutSell;
}
public static function getSubscribedEvents(): array
{
return [
ProductSearchCriteriaEvent::class => 'onProductSearch',
];
}
public function onProductSearch(ProductSearchCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
$preemiumWithoutSellResult = $this->getAllPreemiumWithoutSell->getAllWithoutSell();
$filters = [];
/** @var PremiumEntity $result */
foreach ($preemiumWithoutSellResult as $result) {
if ($result instanceof PremiumEntity && $result->getProduct() !== null) {
$filters[] = new EqualsFilter(
'product.id',
$result->getProduct()->getId()
);
foreach ($result->getProduct()->getChildren() as $variant) {
$filters[] = new EqualsFilter(
'product.id',
$variant->getId()
);
}
}
}
$criteria->addFilter(
new NotFilter(
NotFilter::CONNECTION_OR,
$filters
)
);
}
}