<?php declare(strict_types=1);
namespace GlobusSW6\Subscriber\Biocide;
use GlobusSW6\Service\BiocideApi\BiocideApiService;
use Psr\Log\LoggerInterface;
use Shopware\Core\Content\Product\ProductCollection;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use GlobusSW6\Service\IaneoBusinessExtension;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
class ProductBiocideExtensionSubscriber implements EventSubscriberInterface
{
/** @var LoggerInterface */
private $logger;
/** @var IaneoBusinessExtension */
private $ianeoBusinessExtension;
/** @var BiocideApiService */
private $biocideApiService;
/**
* ProductBiocideExtensionSubscriber constructor.
* @param LoggerInterface $logger
* @param IaneoBusinessExtension $ianeoBusinessExtension
* @param BiocideApiService $biocideApiService
*/
public function __construct(LoggerInterface $logger, IaneoBusinessExtension $ianeoBusinessExtension, BiocideApiService $biocideApiService)
{
$this->logger = $logger;
$this->ianeoBusinessExtension = $ianeoBusinessExtension;
$this->biocideApiService = $biocideApiService;
}
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 {
$biocide = $this->biocideApiService->getBiocideByProductId($product->getId(), $event->getContext());
if($biocide) {
$this->ianeoBusinessExtension->addSingleAttributeToProduct($product, $biocide, 'biocide');
}
} catch(\Exception $exception) {
$this->logger->error(__CLASS__ . ":" . __FUNCTION__ . ":" . __LINE__ . ":\$exception->getMessage(): " . $exception->getMessage());
}
}
}
}
}