<?php declare(strict_types=1);
namespace GlobusSW6\Subscriber\Mdr;
use Shopware\Core\Content\Product\ProductCollection;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use GlobusSW6\Service\MdrApi\MdrApiService;
use Psr\Log\LoggerInterface;
use GlobusSW6\Service\IaneoBusinessExtension;
class ProductMdrExtensionSubscriber implements EventSubscriberInterface
{
/** @var LoggerInterface */
private $logger;
/** @var IaneoBusinessExtension */
private $ianeoBusinessExtension;
/** @var MdrApiService */
private $mdrApiService;
/**
* ProductMdrExtensionSubscriber constructor.
* @param LoggerInterface $logger
* @param IaneoBusinessExtension $ianeoBusinessExtension
* @param MdrApiService $mdrApiService
*/
public function __construct(LoggerInterface $logger, IaneoBusinessExtension $ianeoBusinessExtension, MdrApiService $mdrApiService)
{
$this->logger = $logger;
$this->ianeoBusinessExtension = $ianeoBusinessExtension;
$this->mdrApiService = $mdrApiService;
}
public static function getSubscribedEvents(): array
{
return [
'product.search.result.loaded' => 'onProductLoaded'
];
}
public function onProductLoaded(EntitySearchResultLoadedEvent $event)
{
/** @var ProductCollection $products */
$products = $event->getResult()->getEntities();
if ($products === null) {
return;
}
if ($event->getContext()->getSource() instanceOf SalesChannelApiSource)
{
foreach ($products as $product) {
try {
$mdr = $this->mdrApiService->getMdrByProductId($product->getId(), $event->getContext());
if ($mdr) {
$this->ianeoBusinessExtension->addSingleAttributeToProduct($product, $mdr, 'mdr');
}
} catch (\Exception $exception) {
$this->logger->error(__CLASS__ . ":" . __FUNCTION__ . ":" . __LINE__ . ":\$exception->getMessage(): " . $exception->getMessage());
}
}
}
}
}