<?php declare(strict_types=1);
namespace EnnoDigitalProducts\Subscriber;
use EnnoDigitalProducts\Service\DigitalProductDataService;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Context;
class ProductLoaded implements EventSubscriberInterface
{
/**
* @var SystemConfigService
*/
private $systemConfigService;
private $digitalProductDataservice;
private $salesChannelRepository;
private $container;
private $salesChannelId;
private $salesChannel;
private $pluginConfig;
public function __construct(SystemConfigService $systemConfigService, DigitalProductDataService $digitalProductDataservice, EntityRepositoryInterface $salesChannelRepository, $container)
{
$this->systemConfigService = $systemConfigService;
$this->digitalProductDataservice = $digitalProductDataservice;
$this->salesChannelRepository = $salesChannelRepository;
$this->container = $container;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded'
];
}
private function ennoInit()
{
$salesChannelId = null;
try
{
$requestStack = $this->container->get('request_stack');
if ( $requestStack && method_exists($requestStack, 'getCurrentRequest') )
{
$currentRequest = $requestStack->getCurrentRequest();
if ($currentRequest && method_exists($currentRequest, 'get') )
{
$salesChannelId = $currentRequest->get("sw-sales-channel-id");
}
}
}
catch (\Exception $e) { }
if( !$salesChannelId ) return;
if( $this->salesChannelId === $salesChannelId ) return;
$this->salesChannelId = $salesChannelId;
$this->salesChannel = $this->salesChannelRepository->search(new Criteria([$salesChannelId]), Context::createDefaultContext())->get($salesChannelId);
$this->pluginConfig = $this->systemConfigService->get('EnnoDigitalProducts.config', $salesChannelId);
}
public function onProductsLoaded(EntityLoadedEvent $event): void
{
$this->ennoInit();
if( !is_array($this->pluginConfig) ) return;
if( empty($this->pluginConfig) ) return;
if( !array_key_exists('active', $this->pluginConfig)) return;
if( !$this->pluginConfig["active"] ) return;
/** @var ProductEntity $productEntity */
foreach ($event->getEntities() as $entity)
{
$digitalData = $this->digitalProductDataservice->getProductData($event->getContext(), $entity->getId(), $entity->getParentId());
if($digitalData) $entity->addExtension('ennoDigitalProducts', $digitalData);
// die();
}
}
}