<?php
namespace GrimmTheme\Storefront\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
use Shopware\Storefront\Page\Product\Configurator\ProductCombinationFinder;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductOptionDetailSubscriber implements EventSubscriberInterface
{
private static array $mimeTypeFilter = [
'application/pdf'
];
private SalesChannelRepositoryInterface $productRepository;
private ProductCombinationFinder $productCombinationFinder;
public function __construct(
SalesChannelRepositoryInterface $productRepository,
ProductCombinationFinder $productCombinationFinder
)
{
$this->productRepository = $productRepository;
$this->productCombinationFinder = $productCombinationFinder;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductDetailPage'
];
}
/**
* Instead of using special images for options we are using product cover of the variant article
*
* @param ProductPageLoadedEvent $productPageLoadedEvent
*/
public function onProductDetailPage(ProductPageLoadedEvent $productPageLoadedEvent)
{
$elements = $productPageLoadedEvent->getPage()->getConfiguratorSettings()->getElements();
foreach ($elements as $element) {
if ($element->getDisplayType() === 'media') {
foreach ($element->getOptions() as $option) {
$setting = $option->getConfiguratorSetting();
$combination = $this->productCombinationFinder->find(
$setting->getProductId(),
$option->getGroupId(),
[$setting->getOptionId()],
$productPageLoadedEvent->getSalesChannelContext()
);
$variantId = $combination->getVariantId();
if ($variantId) {
/** @var \Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity $variant */
$variant = $this->productRepository->search(new Criteria([$variantId]), $productPageLoadedEvent->getSalesChannelContext())->first();
if ($variant) {
$cover = $variant->getCoverId();
if ($cover) {
$option->setMediaId($cover);
$option->setMedia($variant->getCover()->getMedia());
$setting->setMediaId($cover);
$setting->setMedia($variant->getCover()->getMedia());
}
}
}
}
}
}
}
}