<?php declare(strict_types=1);
namespace Kilb\KilbShopwareProductDesigner\Subscriber;
use Kilb\KilbShopwareProductDesigner\ArrayCache\ArrayCacheTrait;
use Kilb\KilbShopwareProductDesigner\Services\ConfigurationServiceInterface;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
use ArrayCacheTrait;
/**
* @var ConfigurationServiceInterface
*/
private $configurationService;
/**
* @param ConfigurationServiceInterface $configurationService
*/
public function __construct(ConfigurationServiceInterface $configurationService)
{
$this->configurationService = $configurationService;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return[
ProductPageLoadedEvent::class => 'onProductPageLoaded',
ProductListingResultEvent::class => 'onProductListingResult',
'product.search.result.loaded' => 'onEntitySearchResultLoaded',
];
}
/**
* @param EntitySearchResultLoadedEvent $event
*/
public function onEntitySearchResultLoaded(EntitySearchResultLoadedEvent $event): void
{
foreach ($event->getResult()->getEntities()->getElements() as $product) {
$this->addCustomFields($product, $event->getContext());
}
}
/**
* @param ProductPageLoadedEvent $event
*/
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
$this->addCustomFields($product, $event->getContext());
}
/**
* @param ProductListingResultEvent $event
*/
public function onProductListingResult(ProductListingResultEvent $event): void
{
foreach ($event->getResult()->getElements() as $product) {
$this->addCustomFields($product, $event->getContext());
}
}
/**
* @param ProductEntity $product
* @param Context $context
*/
private function addCustomFields(
ProductEntity $product,
Context $context
): void {
$hasProductDesign = false;
$isBasketButtonDisabled = false;
$configurations = $this->configurationService->getConfigurationsByProductNumber(
$product->getProductNumber(),
$context
);
if (!empty($configurations)) {
$configuration = array_shift($configurations);
$hasProductDesign = true;
$isBasketButtonDisabled = $configuration['isBasketButtonDisabled'];
}
$customFields = $product->getCustomFields();
$customFields['hasProductDesign'] = $hasProductDesign;
$customFields['isBasketButtonDisabled'] = $isBasketButtonDisabled;
$product->setCustomFields($customFields);
}
}