<?php declare(strict_types=1);
namespace Acris\CustomerGroupAvailableProduct\Storefront\Subscriber;
use Acris\CustomerGroupAvailableProduct\Components\DisplayAllowedProductService;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ProductSubscriber implements EventSubscriberInterface
{
/**
* @var DisplayAllowedProductService
*/
private $displayProductService;
/**
* @var SystemConfigService
*/
private $configService;
public function __construct(DisplayAllowedProductService $displayProductService, SystemConfigService $configService)
{
$this->displayProductService = $displayProductService;
$this->configService = $configService;
}
public static function getSubscribedEvents(): array
{
return[
ProductPageLoadedEvent::class => 'onProductLoaded'
];
}
public function onProductLoaded(ProductPageLoadedEvent $event)
{
$productId = $event->getPage()->getProduct()->getId();
if(empty($productId)) {
return;
}
if($this->configService->get('AcrisCustomerGroupAvailableProductCS.config.releaseProductsIfNoCustomerGroupAssigned', $event->getSalesChannelContext()->getSalesChannel()->getId()) === DisplayAllowedProductService::DEFAULT_PLUGIN_CONFIG_RELEASE_PRODUCT_IF_NO_CUSTOMER_GROUPS_ASSIGNED && $this->displayProductService->checkIfNoCustomerGroupsAssigned($productId, $event->getSalesChannelContext()->getContext())) return;
$blockedProductIds = $this->displayProductService->getDisplayProductIdsForCustomerGroupId($event->getSalesChannelContext()->getCurrentCustomerGroup()->getId(), $event->getContext());
if(!in_array($productId, $blockedProductIds)) {
throw new NotFoundHttpException();
}
}
}