<?php declare(strict_types=1);
namespace ChespackTheme\Service;
use Shopware\Core\Content\Category\CategoryCollection;
use Shopware\Core\Content\Category\Service\NavigationLoaderInterface;
use Shopware\Core\Content\Category\Tree\TreeItem;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Event\StorefrontRenderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Add additional data to the page
*/
class AddDataToPage implements EventSubscriberInterface
{
protected SystemConfigService $systemConfig;
private NavigationLoaderInterface $navigationLoader;
public function __construct(
SystemConfigService $systemConfig,
NavigationLoaderInterface $navigationLoader
) {
$this->systemConfig = $systemConfig;
$this->navigationLoader = $navigationLoader;
}
public static function getSubscribedEvents(): array
{
return [
StorefrontRenderEvent::class => 'addContentCategories'
];
}
/**
* Add content menu
*
* @param StorefrontRenderEvent $event
*/
public function addContentCategories(StorefrontRenderEvent $event): void
{
$context = $event->getSalesChannelContext();
$entity = new ArrayEntity($this->getContentMenu($context));
$context->addExtension('content_categories', $entity);
}
/**
* Get content menu by category ID
*
* @param SalesChannelContext $context
* @return array
*/
private function getContentMenu(SalesChannelContext $context): array
{
$contentMenu = [];
$categoryId = $this->systemConfig->get('ChespackTheme.config.contentCategory', $context->getSalesChannelId());
if ($categoryId === null) {
return [];
}
$navigation = $this->navigationLoader->load($categoryId, $context, $categoryId, 4);
$mainCats = new CategoryCollection(array_map(static function (TreeItem $treeItem) {
return $treeItem->getCategory();
}, $navigation->getTree()));
foreach ($mainCats as $mainCat) {
$mainCatNav = $this->navigationLoader->load($mainCat->get('id'), $context, $mainCat->get('id'), 4);
$mainCatChildren = new CategoryCollection(array_map(static function (TreeItem $treeItem) {
return $treeItem->getCategory();
}, $mainCatNav->getTree()));
$mainCat->children = $mainCatChildren;
array_push($contentMenu, $mainCat);
}
return $contentMenu;
}
}