<?php declare(strict_types=1);
namespace GlobusSW6\Subscriber\ArticleDocuments;
use GlobusSW6\Service\ArticleDocumentsService;
use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use GlobusSW6\Service\IaneoBusinessExtension;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Content\Product\ProductCollection;
use Symfony\Component\HttpFoundation\RequestStack;
class HandleArticleDocuments implements EventSubscriberInterface
{
private ArticleDocumentsService $articleDocumentsService;
private LoggerInterface $logger;
private IaneoBusinessExtension $IaneoBusinessExtension;
private RequestStack $requestStack;
public const WHITELIST_ROUTES = [
'frontend.detail.page',
'store-api.product.detail',
];
public function __construct(
ArticleDocumentsService $articleDocumentsService,
LoggerInterface $logger,
IaneoBusinessExtension $IaneoBusinessExtension,
RequestStack $requestStack
) {
$this->articleDocumentsService = $articleDocumentsService;
$this->logger = $logger;
$this->IaneoBusinessExtension = $IaneoBusinessExtension;
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents(): array
{
return [
// ProductPageLoadedEvent::class => 'onProductPageLoadedEvent'
'product.search.result.loaded' => 'onProductLoaded'
];
}
public function onProductLoaded(EntitySearchResultLoadedEvent $event)
{
// do not fire event in backend context
if ($event->getContext()->getSource() instanceof AdminApiSource) {
if ($event->getContext()->getSource()->isAdmin()) {
return;
}
}
if(!$this->shouldAttachDocuments()) {
return;
}
/** @var ProductCollection $products */
$products = $event->getResult()->getEntities();
if($products === null){
return;
}
foreach ($products as $product) {
try {
$articleDocuments = $this->articleDocumentsService->getProductDocumentRelations($product->getId(), $event->getContext());
if($articleDocuments->has('documents')) {
$this->IaneoBusinessExtension->addSingleAttributeToProduct($product, $articleDocuments->get('documents'), 'articleDocuments');
}
} catch(\Exception $exception) {
$this->logger->error(__CLASS__ . ":" . __FUNCTION__ . ":" . __LINE__ . ":\$exception->getMessage(): " . $exception->getMessage());
}
}
}
private function shouldAttachDocuments(): bool
{
$currentRequest = $this->requestStack->getCurrentRequest();
if ($currentRequest) {
$requestRoute = $currentRequest->attributes?->get('_route') ?? '';
foreach (self::WHITELIST_ROUTES as $WHITELIST_ROUTE) {
if (str_contains($requestRoute, $WHITELIST_ROUTE)) {
return true;
}
}
}
return false;
}
}