custom/plugins/AcrisCategoryCustomerGroupCS/src/Subscriber/CategorySubscriber.php line 45

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Acris\CategoryCustomerGroup\Subscriber;
  3. use Acris\CategoryCustomerGroup\Components\BlockCategoryService;
  4. use Shopware\Core\Content\Category\Event\NavigationLoadedEvent;
  5. use Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  8. class CategorySubscriber implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @var BlockCategoryService
  12.      */
  13.     private $blockCategoryService;
  14.     public function __construct(BlockCategoryService $blockCategoryService)
  15.     {
  16.         $this->blockCategoryService $blockCategoryService;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return[
  21.             NavigationPageLoadedEvent::class => 'onNavigationPageLoaded',
  22.             NavigationLoadedEvent::class => 'onNavigationLoaded'
  23.         ];
  24.     }
  25.     public function onNavigationPageLoaded(NavigationPageLoadedEvent $event)
  26.     {
  27.         $navigationId $event->getRequest()->get('navigationId'$event->getSalesChannelContext()->getSalesChannel()->getNavigationCategoryId());
  28.         if(empty($navigationId)) {
  29.             return;
  30.         }
  31.         $blockedCategoryIds $this->blockCategoryService->getBlockedCategoryIdsForCustomerGroupId($event->getSalesChannelContext()->getCurrentCustomerGroup()->getId(), $event->getContext());
  32.         if(in_array($navigationId$blockedCategoryIds)) {
  33.             throw new NotFoundHttpException();
  34.         }
  35.     }
  36.     public function onNavigationLoaded(NavigationLoadedEvent $event): void
  37.     {
  38.         $blockedCategoryIds $this->blockCategoryService->getBlockedCategoryIdsForCustomerGroupId($event->getSalesChannelContext()->getCurrentCustomerGroup()->getId(), $event->getContext());
  39.         $navigation $event->getNavigation();
  40.         $convertedTreeItems = [];
  41.         foreach ($navigation->getTree() as $treeItem) {
  42.             if($this->blockCategoryService->blockCategory($treeItem$blockedCategoryIds) === false) {
  43.                 continue;
  44.             }
  45.             array_push($convertedTreeItems$treeItem);
  46.         }
  47.         $navigation->setTree($convertedTreeItems);
  48.     }
  49. }