<?php
declare(strict_types=1);
namespace Wbfk\ProductDownloads\Subscriber;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Context;
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 Shopware\Storefront\Page\Product\QuickView\MinimalQuickViewPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepository
*/
private EntityRepository $productDownloadRepository;
public function __construct(EntityRepository $productDownloadRepository)
{
$this->productDownloadRepository = $productDownloadRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageCriteriaEvent::class => 'onProductCriteriaLoaded',
ProductPageLoadedEvent::class => 'loadProductPage',
MinimalQuickViewPageLoadedEvent::class => 'loadMinimalQuickViewPage',
];
}
public function onProductCriteriaLoaded(ProductPageCriteriaEvent $event): void
{
$event->getCriteria()->addAssociation('wbfk_product_download');
}
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();
$this->addWbfkDownloadExtension($product, $event->getContext());
}
public function loadMinimalQuickViewPage(MinimalQuickViewPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
$this->addWbfkDownloadExtension($product, $event->getContext());
}
private function addWbfkDownloadExtension(ProductEntity $product, Context $context)
{
$productDownloads = $product->getExtension('wbfk_product_download');
$productId = $product->getParentId() ?? $product->getId();
if ($productId && (!$productDownloads || count($productDownloads->getElements()) === 0)) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $productId));
$parentDownloads = $this->productDownloadRepository->search($criteria, $context)->getEntities();
if ($parentDownloads->count() > 0) {
$product->addExtension('wbfk_product_download', new StructCollection($parentDownloads->getElements()));
}
}
}
}