<?php
/**
* gpl-3.0 license
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @package shop.liebscher-bracht.com
* @author Michael Lämmlein <michael.laemmlein@liebscher-bracht.com>
* @copyright ©2024 Liebscher & Bracht
* @license https://www.gnu.org/licenses/gpl-3.0.html
* @version 1.0.0
* @since 18.09.24
*/
declare(strict_types=1);
namespace Lnb\Shopware6\LnbThemeDefault\Subscriber;
use Shopware\Core\Content\Category\Tree\TreeItem;
use Shopware\Core\Content\Media\MediaCollection;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HeaderPageletLoadedSubscriber implements EventSubscriberInterface
{
public function __construct(
#[Target('media.repository')] private readonly EntityRepository $mediaRepository
) {
}
public static function getSubscribedEvents(): array
{
return [
HeaderPageletLoadedEvent::class => 'onHeaderPageletLoaded'
];
}
public function onHeaderPageletLoaded(HeaderPageletLoadedEvent $event)
{
$ids = $this->collectIds($event->getPagelet()->getNavigation()->getTree(), []);
$mediaCollection = $this->searchMedia($ids, $event->getContext());
$event->getPagelet()->addExtension('lnb_theme_default_category_navigation_icons', new ArrayStruct([
'mediaCollection' => $mediaCollection
]));
}
private function collectIds(array $tree, array $ids): array
{
/** @var TreeItem $item */
foreach ($tree as $item) {
if ($item->getChildren() > 0) {
$ids = $this->collectIds($item->getChildren(), $ids);
}
$customFields = $item->getCategory()->getCustomFields();
if (!isset($customFields['custom_configurations_category_navigation_icon'])
|| !$customFields['custom_configurations_category_navigation_icon']
) {
continue;
}
$ids[] = $customFields['custom_configurations_category_navigation_icon'];
}
return $ids;
}
private function searchMedia(array $ids, Context $context): MediaCollection
{
if (empty($ids)) {
return new MediaCollection();
}
$criteria = new Criteria($ids);
/** @var MediaCollection $media */
$media = $this->mediaRepository
->search($criteria, $context)
->getEntities();
return $media;
}
}