<?php declare(strict_types=1);
namespace Acris\ProductInfoText\Subscriber;
use Acris\ProductInfoText\Components\ProductInfoText\InfoTextGateway;
use Acris\ProductInfoText\Components\ProductInfoText\InfoTextService;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductLoadedSubscriber implements EventSubscriberInterface
{
public const ACRIS_STREAM_IDS_EXTENSION = 'acrisStreamIds';
/**
* @var EntityRepositoryInterface
*/
private $productRepository;
/**
* @var InfoTextService
*/
private $infoTextService;
/**
* @var InfoTextGateway
*/
private $infoTextGateway;
public function __construct(
EntityRepositoryInterface $productRepository,
InfoTextService $infoTextService,
InfoTextGateway $infoTextGateway
) {
$this->productRepository = $productRepository;
$this->infoTextService = $infoTextService;
$this->infoTextGateway = $infoTextGateway;
}
public static function getSubscribedEvents()
{
return [
ProductPageLoadedEvent::class => ['productLoaded', 200]
];
}
public function productLoaded(ProductPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
if ($product->hasExtension(self::ACRIS_STREAM_IDS_EXTENSION) && !empty($product->getExtension(self::ACRIS_STREAM_IDS_EXTENSION))) {
$productStreamIds = $product->getExtension(self::ACRIS_STREAM_IDS_EXTENSION)->get('ids');
} else {
$productStreamIds = $this->infoTextGateway->getProductStreamIds([$product->getId()], $event->getSalesChannelContext()->getContext());
$product->addExtension(self::ACRIS_STREAM_IDS_EXTENSION, new ArrayEntity(['ids' => $productStreamIds]));
}
if (empty($productStreamIds)) return;
$infoTextResult = $this->infoTextGateway->getProductDetailInfoText($productStreamIds, $event->getSalesChannelContext());
if(empty($infoTextResult) || $infoTextResult->count() === 0) {
return;
}
$infoTexts = $this->infoTextService->getInfoTextsForProduct($infoTextResult->getEntities());
$product->addExtension('acrisInfoText', new ArrayEntity([
'texts' => $infoTexts
]));
}
}