<?php declare(strict_types=1);
namespace Nd\Theme\Subscriber;
use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
use Shopware\Core\Content\Cms\SalesChannel\Struct\TextStruct;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Shopware\Storefront\Pagelet\Menu\Offcanvas\MenuOffcanvasPageletLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
class AddMenuData implements EventSubscriberInterface
{
public function __construct(EntityRepository $categoryRepository, array $additionalMenus)
{
$this->categoryRepository = $categoryRepository;
$this->additionalMenus = $additionalMenus;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
HeaderPageletLoadedEvent::class => 'addData',
MenuOffcanvasPageletLoadedEvent::class => 'addDataOffcanvas'
];
}
public function addData(HeaderPageletLoadedEvent $event)
{
if(!$this->additionalMenus){
return;
}
$pagelet = $event->getPagelet();
$additionalMenus = $this->loadAdditionalMenus($event->getContext());
$pagelet->addExtension('additional_menus', $additionalMenus);
}
public function addDataOffcanvas(MenuOffcanvasPageletLoadedEvent $event)
{
if (!$this->additionalMenus) {
return;
}
$pagelet = $event->getPagelet();
$additionalMenus = $this->loadAdditionalMenus($event->getContext());
$pagelet->addExtension('additional_menus', $additionalMenus);
}
public function getMenu($id, $context)
{
$criteria = new Criteria();
$criteria->addAssociation('seoUrls.urls');
$criteria->addFilter(new EqualsFilter('active', true));
$criteria->addFilter(new EqualsFilter('parentId', $id));
$categories = $this->categoryRepository->search($criteria, $context);
if ($categories->count() == 0) {
return [];
}
return $categories->getEntities()->sortByPosition();
}
private function loadAdditionalMenus(Context $context): ArrayStruct
{
$additionalMenus = new ArrayStruct();
foreach($this->additionalMenus as $topMenuKey => $topMenuId){
$additionalMenus->set($topMenuKey, $this->getMenu($topMenuId, $context));
}
return $additionalMenus;
}
}