<?php declare(strict_types=1);
namespace Crehler\VariantsAdvanced\Subscriber;
use Crehler\VariantsAdvanced\Struct\ParentProduct;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
private SalesChannelRepositoryInterface $productRepository;
public function __construct(SalesChannelRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoaded'
];
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
$parentName = null;
if ($product->getParentId() !== null) {
/** @var SalesChannelProductEntity $parent */
$parent = $this->productRepository->search(new Criteria([$product->getParentId()]), $event->getSalesChannelContext())->first();
if ($parent !== null) {
$parentName = $parent->getTranslation('name');
}
}
$product->addExtension('parentProduct', (new ParentProduct())->setName($parentName));
}
}