<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AddEnergyDataFileMediaToProduct implements EventSubscriberInterface
{
public function __construct(private readonly EntityRepository $mediaRepository)
{
}
public static function getSubscribedEvents()
{
return [
'sales_channel.product.loaded' => 'onProductLoaded',
];
}
public function onProductLoaded(SalesChannelEntityLoadedEvent $event): void
{
$products = $event->getEntities();
$productsWithEnergyDataFileMedia = [];
$energyDataFileMediaIds = [];
foreach ($products as $product) {
$energyDataFileMediaId = $product->getCustomFields()['wbfk_product_energylabel_datasheet_file'] ?? null;
if ($energyDataFileMediaId) {
$energyDataFileMediaIds[] = $energyDataFileMediaId;
$productsWithEnergyDataFileMedia[] = $product;
}
}
if (count($energyDataFileMediaIds) > 0) {
$this->addEnergyDataFileMediaToProducts($productsWithEnergyDataFileMedia, $energyDataFileMediaIds, $event);
}
}
private function addEnergyDataFileMediaToProducts(
array $products,
array $energyDataFileMediaIds,
SalesChannelEntityLoadedEvent $event
): void {
$medias = $this->mediaRepository->search(
(new Criteria())->addFilter(new EqualsAnyFilter('id', $energyDataFileMediaIds)),
$event->getContext()
);
foreach ($products as $product){
$product->addExtension('wbfk_energy_data_file_media', $medias->get($product->getCustomFields()['wbfk_product_energylabel_datasheet_file']));
}
}
}