<?php declare(strict_types=1);
namespace Crehler\ProductFiles\Subscriber;
use Crehler\ProductFiles\Service\ProductFilesService;
use Shopware\Storefront\Page\Product\ProductLoaderCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
/**
* @var ProductFilesService
*/
private $productFilesService;
public function __construct(ProductFilesService $productFilesService)
{
$this->productFilesService = $productFilesService;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
ProductPageCriteriaEvent::class => 'onProductLoaderCriteria',
ProductPageLoadedEvent::class => 'onProductsLoaded',
];
}
public function onProductsLoaded(ProductPageLoadedEvent $event)
{
$page = $event->getPage();
$product = $page->getProduct();
$context = $event->getSalesChannelContext();
$productFiles = $this->productFilesService->prepareProductFiles($product, $context);
$product->addExtension('productFiles', $productFiles);
}
/**
* @param ProductLoaderCriteriaEvent $event
*/
public function onProductLoaderCriteria(ProductPageCriteriaEvent $event)
{
try {
$event
->getCriteria()
->addAssociation('downloadFiles')
->addAssociation('downloadFilesLinks');
} catch (\Exception $e) {
}
}
}