<?php declare(strict_types=1);
namespace Samson\Subscriber;
/***
*
* This file is part of the "SAMSON Shop" project.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2022
*
***/
use Samson\CustomFieldSet\Constants\ProductCustomFieldConstants;
use Shopware\Core\Content\Media\MediaEntity;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductListingResultSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $mediaRepository;
public function __construct(EntityRepositoryInterface $mediaRepository)
{
$this->mediaRepository = $mediaRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LISTING_RESULT => 'onProductListingResult'
];
}
public function onProductListingResult(ProductListingResultEvent $event)
{
$context = $event->getContext();
$event->getResult()->map(function (SalesChannelProductEntity $product) use ($context) {
// todo: fetch all media ONCE
$this->setProductBackgroundImage($product, $context);
});
}
private function setProductBackgroundImage(SalesChannelProductEntity $salesChannelProductEntity, Context $context): void
{
if (!isset($salesChannelProductEntity->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_SHOW_BACKGROUND_IMAGE])) {
return;
}
$showBackgroundImage = $salesChannelProductEntity->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_SHOW_BACKGROUND_IMAGE];
if ($showBackgroundImage) {
if (!isset($salesChannelProductEntity->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_BACKGROUND_IMAGE])) {
return;
}
$mediaId = $salesChannelProductEntity->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_BACKGROUND_IMAGE];
if ($mediaId instanceof MediaEntity) {
return;
}
$media = $this->mediaRepository->search(new Criteria([$mediaId]), $context)->first();
if (!is_null($media)) {
$customFields = $salesChannelProductEntity->getCustomFields();
$customFields[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_BACKGROUND_IMAGE] = $media;
$salesChannelProductEntity->setCustomFields($customFields);
}
}
}
}