<?php declare(strict_types=1);
namespace Crehler\AsusEngine\Subscriber;
use phpDocumentor\Reflection\Types\Null_;
use Shopware\Core\Content\Category\CategoryEvents;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CategorySubscriber implements EventSubscriberInterface
{
private const PHOTO_KEYS = ['custom_mega_menu_first', 'custom_mega_menu_second'];
private EntityRepositoryInterface $mediaRepository;
public function __construct(
EntityRepositoryInterface $mediaRepository
)
{
$this->mediaRepository = $mediaRepository;
}
public static function getSubscribedEvents(): array
{
return [
CategoryEvents::CATEGORY_LOADED_EVENT => 'onCategoryLoaded',
];
}
public function onCategoryLoaded(EntityLoadedEvent $event): void
{
$context = $event->getContext();
if (!$context->getSource() instanceof SalesChannelApiSource) {
return;
}
foreach ($event->getEntities() as $entity) {
$customFields = $entity->get('customFields');
if ($customFields) {
foreach (self::PHOTO_KEYS as $key) {
if (!array_key_exists($key, $customFields)) {
continue;
}
$mediaEntity = $this->mediaRepository->search(new Criteria([$customFields[$key]]), $context)->first();
$entity->addExtension($key, $mediaEntity);
}
}
}
}
}