<?php declare(strict_types=1);
namespace Wyn\CustomerTheme\Subscriber;
use Shopware\Core\Content\Category\CategoryEntity;
use Shopware\Core\Content\Category\Event\NavigationLoadedEvent;
use Shopware\Core\Content\Media\MediaCollection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\Framework\Struct\ArrayStruct as ArrayStructAlias;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
class NavigationSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $mediaRepository;
/**
* @param EntityRepositoryInterface $mediaRepository
*/
public function __construct(EntityRepositoryInterface $mediaRepository)
{
$this->mediaRepository = $mediaRepository;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
NavigationLoadedEvent::class => 'onNavigationLoaded'
];
}
public function onNavigationLoaded(NavigationLoadedEvent $event)
{
$navigationTree = $event->getNavigation()->getTree();
$categoryIconMediaIds = [];
foreach($navigationTree as $treeItem) {
$children = $treeItem->getChildren();
/** @var CategoryEntity $child */
foreach($children as $child) {
$iconMediaId = $child->getCategory()->getCustomFields()['wyn_category_additional_information_icon'] ?? null;
if($iconMediaId != null) {
$categoryIconMediaIds[] = $iconMediaId;
}
}
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsAnyFilter('id', $categoryIconMediaIds));
/** @var MediaCollection $result */
$mediaCollection = $this->mediaRepository->search($criteria, $event->getContext())->getEntities();
// $event->getNavigation()->addExtension('categoryIconMediaCollection', new ArrayStruct(['mediaCollection' => $mediaCollection]));
$struct = new ArrayStruct(['mediaCollection' => $mediaCollection]);
$event->getNavigation()->addExtension('categoryIconMediaCollection', $struct);
$hallo = 5;
}
}