custom/plugins/CrehlerAsusEngine/src/Subscriber/CategorySubscriber.php line 33

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Crehler\AsusEngine\Subscriber;
  3. use phpDocumentor\Reflection\Types\Null_;
  4. use Shopware\Core\Content\Category\CategoryEvents;
  5. use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class CategorySubscriber implements EventSubscriberInterface
  11. {
  12.     private const PHOTO_KEYS = ['custom_mega_menu_first''custom_mega_menu_second'];
  13.     private EntityRepositoryInterface $mediaRepository;
  14.     public function __construct(
  15.         EntityRepositoryInterface $mediaRepository
  16.     )
  17.     {
  18.         $this->mediaRepository $mediaRepository;
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             CategoryEvents::CATEGORY_LOADED_EVENT => 'onCategoryLoaded',
  24.         ];
  25.     }
  26.     public function onCategoryLoaded(EntityLoadedEvent $event): void
  27.     {
  28.         $context $event->getContext();
  29.         if (!$context->getSource() instanceof SalesChannelApiSource) {
  30.             return;
  31.         }
  32.         foreach ($event->getEntities() as $entity) {
  33.             $customFields $entity->get('customFields');
  34.             if ($customFields) {
  35.                 foreach (self::PHOTO_KEYS as $key) {
  36.                     if (!array_key_exists($key$customFields)) {
  37.                         continue;
  38.                     }
  39.                     $mediaEntity $this->mediaRepository->search(new Criteria([$customFields[$key]]), $context)->first();
  40.                     $entity->addExtension($key$mediaEntity);
  41.                 }
  42.             }
  43.         }
  44.     }
  45. }