<?php declare(strict_types=1);
namespace Acris\CategoryCustomerGroup\Subscriber;
use Acris\CategoryCustomerGroup\Components\BlockCategoryService;
use Shopware\Core\Content\Category\Event\NavigationLoadedEvent;
use Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CategorySubscriber implements EventSubscriberInterface
{
/**
* @var BlockCategoryService
*/
private $blockCategoryService;
public function __construct(BlockCategoryService $blockCategoryService)
{
$this->blockCategoryService = $blockCategoryService;
}
public static function getSubscribedEvents(): array
{
return[
NavigationPageLoadedEvent::class => 'onNavigationPageLoaded',
NavigationLoadedEvent::class => 'onNavigationLoaded'
];
}
public function onNavigationPageLoaded(NavigationPageLoadedEvent $event)
{
$navigationId = $event->getRequest()->get('navigationId', $event->getSalesChannelContext()->getSalesChannel()->getNavigationCategoryId());
if(empty($navigationId)) {
return;
}
$blockedCategoryIds = $this->blockCategoryService->getBlockedCategoryIdsForCustomerGroupId($event->getSalesChannelContext()->getCurrentCustomerGroup()->getId(), $event->getContext());
if(in_array($navigationId, $blockedCategoryIds)) {
throw new NotFoundHttpException();
}
}
public function onNavigationLoaded(NavigationLoadedEvent $event): void
{
$blockedCategoryIds = $this->blockCategoryService->getBlockedCategoryIdsForCustomerGroupId($event->getSalesChannelContext()->getCurrentCustomerGroup()->getId(), $event->getContext());
$navigation = $event->getNavigation();
$convertedTreeItems = [];
foreach ($navigation->getTree() as $treeItem) {
if($this->blockCategoryService->blockCategory($treeItem, $blockedCategoryIds) === false) {
continue;
}
array_push($convertedTreeItems, $treeItem);
}
$navigation->setTree($convertedTreeItems);
}
}