<?php declare(strict_types=1);
namespace EWHeaderFooter\Subscriber;
use Shopware\Core\Content\Category\CategoryCollection;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class NavigationLoadedSubscriber implements EventSubscriberInterface
{
public EntityRepository $categoryRepository;
public SystemConfigService $systemConfigService;
public function __construct(
EntityRepository $categoryRepository,
SystemConfigService $systemConfigService)
{
$this->categoryRepository = $categoryRepository;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents()
{
return [
NavigationPageLoadedEvent::class => 'onNavigationPageLoaded',
ProductPageLoadedEvent::class => 'onProductPageLoaded',
];
}
public function onNavigationPageLoaded(PageLoadedEvent $event)
{
$minimalFooterCategoryId = $this->systemConfigService->get('EWHeaderFooter.config.minimalFooterCategoryId');
if ($minimalFooterCategoryId) {
$minimalFooterCategory = $this->getCategory($minimalFooterCategoryId, $event->getContext());
$event->getPage()->getHeader()->getNavigation()->getActive()->setExtensions(['minimalFooterNavigation' => $minimalFooterCategory->getElements()]);
}
}
private function getCategory(string $categoryId, Context $context): CategoryCollection
{
$criteria = new Criteria();
$criteria->addAssociation('translation');
$criteria->addFilter(new EqualsFilter('parentId', $categoryId));
$criteria->addSorting(new FieldSorting('autoIncrement'));
$criteria->addAssociation("media");
/** @var CategoryCollection $category */
$category = $this->categoryRepository->search($criteria, $context)->getEntities();
return $category;
}
public function onProductPageLoaded($event)
{
$minimalFooterCategoryId = $this->systemConfigService->get('EWHeaderFooter.config.minimalFooterCategoryId');
if ($minimalFooterCategoryId) {
$minimalFooterCategory = $this->getCategory($minimalFooterCategoryId, $event->getContext());
$event->getPage()->getHeader()->getNavigation()->getActive()->setExtensions(['minimalFooterNavigation' => $minimalFooterCategory->getElements()]);
}
}
}