<?php declare(strict_types=1);
namespace Acris\CategoryCustomerGroup\Subscriber;
use Acris\CategoryCustomerGroup\Components\BlockCategoryService;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductSuggestCriteriaEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NotFilter;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductListingFeaturesSubscriber implements EventSubscriberInterface
{
/**
* @var BlockCategoryService
*/
private $blockCategoryService;
/**
* @var SystemConfigService
*/
private $configService;
public function __construct(BlockCategoryService $blockCategoryService, SystemConfigService $configService)
{
$this->blockCategoryService = $blockCategoryService;
$this->configService = $configService;
}
public static function getSubscribedEvents()
{
return [
ProductListingCriteriaEvent::class => [
['handleListingRequest', 200]
],
ProductSuggestCriteriaEvent::class => [
['handleSearchRequest', 200]
],
ProductSearchCriteriaEvent::class => [
['handleSearchRequest', 200]
]
];
}
public function handleListingRequest(ProductListingCriteriaEvent $event): void
{
if(!$this->configService->get('AcrisCategoryCustomerGroupCS.config.hideAssignedProductsForOtherCategories', $event->getSalesChannelContext()->getSalesChannel()->getId())) {
return;
}
$this->addBlockedCategoryIdsForCriteria($event->getCriteria(), $event->getSalesChannelContext());
}
public function handleSearchRequest(ProductListingCriteriaEvent $event): void
{
if(!$this->configService->get('AcrisCategoryCustomerGroupCS.config.hideAssignedProductsForSearch', $event->getSalesChannelContext()->getSalesChannel()->getId())) {
return;
}
$this->addBlockedCategoryIdsForCriteria($event->getCriteria(), $event->getSalesChannelContext());
}
private function addBlockedCategoryIdsForCriteria(Criteria $criteria, SalesChannelContext $salesChannelContext)
{
$blockedCategoryIds = $this->blockCategoryService->getBlockedCategoryIdsForCustomerGroupId($salesChannelContext->getCurrentCustomerGroup()->getId(), $salesChannelContext->getContext());
if(empty($blockedCategoryIds) === true) {
return;
}
$criteria->addFilter(new NotFilter(NotFilter::CONNECTION_AND, [new EqualsAnyFilter('product.categories.id', $blockedCategoryIds)]));
}
}