<?php
declare(strict_types=1);
namespace Wbfk\ProductLinks\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Struct\StructCollection;
use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepository
*/
private EntityRepository $productLinkRepository;
public function __construct(EntityRepository $productLinkRepository)
{
$this->productLinkRepository = $productLinkRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageCriteriaEvent::class => 'onProductCriteriaLoaded',
ProductPageLoadedEvent::class => 'loadProductPage',
];
}
public function onProductCriteriaLoaded(ProductPageCriteriaEvent $event): void
{
$event->getCriteria()->addAssociation('wbfk_product_link');
}
public function loadProductPage(ProductPageLoadedEvent $event): void
{
// ToDo: This is a Fallback
// We can not set the product extension to "inherited".
// This would throw an error in the administration on saving a child product
// See: ProductExtension Definition
$product = $event->getPage()->getProduct();
$productLinks = $product->getExtension('wbfk_product_link');
$parentId = $product->getParentId();
if ($parentId && (!$productLinks || count($productLinks->getElements()) == 0)) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $parentId));
$parentProductLinks = $this->productLinkRepository->search($criteria, $event->getContext())->getEntities();
if ($parentProductLinks->count() > 0) {
$product->addExtension('wbfk_product_link', new StructCollection($parentProductLinks->getElements()));
}
}
}
}