custom/plugins/WbfkExtensions/src/Subscriber/AddEnergyDataFileMediaToProduct.php line 28

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace WbfkExtensions\Subscriber;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  7. use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. class AddEnergyDataFileMediaToProduct implements EventSubscriberInterface
  10. {
  11.     public function __construct(private readonly EntityRepository $mediaRepository)
  12.     {
  13.     }
  14.     public static function getSubscribedEvents()
  15.     {
  16.         return [
  17.             'sales_channel.product.loaded' => 'onProductLoaded',
  18.         ];
  19.     }
  20.     public function onProductLoaded(SalesChannelEntityLoadedEvent $event): void
  21.     {
  22.         $products $event->getEntities();
  23.         $productsWithEnergyDataFileMedia = [];
  24.         $energyDataFileMediaIds = [];
  25.         foreach ($products as $product) {
  26.             $energyDataFileMediaId $product->getCustomFields()['wbfk_product_energylabel_datasheet_file'] ?? null;
  27.             if ($energyDataFileMediaId) {
  28.                 $energyDataFileMediaIds[] = $energyDataFileMediaId;
  29.                 $productsWithEnergyDataFileMedia[] = $product;
  30.             }
  31.         }
  32.         if (count($energyDataFileMediaIds) > 0) {
  33.             $this->addEnergyDataFileMediaToProducts($productsWithEnergyDataFileMedia$energyDataFileMediaIds$event);
  34.         }
  35.     }
  36.     private function addEnergyDataFileMediaToProducts(
  37.         array $products,
  38.         array $energyDataFileMediaIds,
  39.         SalesChannelEntityLoadedEvent $event
  40.     ): void {
  41.         $medias $this->mediaRepository->search(
  42.             (new Criteria())->addFilter(new EqualsAnyFilter('id'$energyDataFileMediaIds)),
  43.             $event->getContext()
  44.         );
  45.         foreach ($products as $product){
  46.             $product->addExtension('wbfk_energy_data_file_media'$medias->get($product->getCustomFields()['wbfk_product_energylabel_datasheet_file']));
  47.         }
  48.     }
  49. }