<?phpdeclare(strict_types=1);namespace ApoShop\Subscribers;use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Shopware\Core\Content\Product\ProductEvents;use Shopware\Core\Content\Media\MediaEntity;use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;use Shopware\Core\Content\Product\Aggregate\ProductMedia\ProductMediaEntity;use Shopware\Core\Framework\Uuid\Uuid;use Shopware\Core\Content\Product\Aggregate\ProductMedia\ProductMediaCollection;use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;class ProductSubscriber implements EventSubscriberInterface { private $mediaRepository; private $defaultMediaId = null; public function __construct( EntityRepositoryInterface $mediaRepository ) { $this->mediaRepository = $mediaRepository; } public static function getSubscribedEvents(): array { return [ ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded' ]; } public function onProductsLoaded(EntityLoadedEvent $event) { //return; foreach ($event->getEntities() as $entity) { $defaultMediaId = null; $customFields = $entity->getCustomFields(); if (empty($customFields['pzn'])) { continue; } try{ $defaultMediaId = $this->_getDefaultMediaId(); } catch(\Exception $e){ continue; } if( !$defaultMediaId ){ continue; } $pzn = $customFields['pzn']; $url = 'https://cdn8.apopixx.de/400/web_schraeg/243/' . $pzn . '.jpg'; $pathInfo = pathinfo($url); $media = new MediaEntity(); $media->setId($defaultMediaId); $media->setUrl($url); $media->setMimeType(sprintf('image/%s', $pathInfo['extension'])); $media->setFileExtension($pathInfo['extension']); $media->setFileName($pathInfo['filename']); $productMediaEntity = new ProductMediaEntity(); $productMediaEntity->setId(Uuid::randomHex()); $productMediaEntity->setMedia($media); $productMediaEntity->setPosition(0); $mediaCollection = new ProductMediaCollection([$productMediaEntity]); $entity->setMedia($mediaCollection); if ($entity->getCover() === null) { $entity->setCover($productMediaEntity); } else { $entity->getCover()->setMedia($productMediaEntity->getMedia()); } } } private function _getDefaultMediaId(){ if( $this->defaultMediaId === null ){ try{ $criteria = new Criteria(); $criteria->setLimit(1); $defaultMediaObj = $this->mediaRepository->search( $criteria, \Shopware\Core\Framework\Context::createDefaultContext() )->first(); if( $defaultMediaObj && $defaultMediaObj->getId() ){ $this->defaultMediaId = $defaultMediaObj->getId(); } else{ $this->defaultMediaId = false; } } catch(\Exception $e){ } } return $this->defaultMediaId; }}