<?php
namespace GlobusSW6\Subscriber;
use GlobusSW6\Core\IaneoDefaults;
use GlobusSW6\Service\IaneoBusinessExtension;
use GlobusSW6\Service\ShippingCostsService;
use Psr\Log\LoggerInterface;
use Shopware\Core\Content\Product\ProductCollection;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ShippingCostsSubscriber implements EventSubscriberInterface
{
/** @var ShippingCostsService */
private $shippingCostsService;
/** @var IaneoBusinessExtension */
private $ianeoBusinessExtensionService;
/** @var LoggerInterface */
private $logger;
/**
* @param ShippingCostsService $shippingCostsService
* @param IaneoBusinessExtension $ianeoBusinessExtensionService
* @param LoggerInterface $logger
*/
public function __construct(ShippingCostsService $shippingCostsService, IaneoBusinessExtension $ianeoBusinessExtensionService, LoggerInterface $logger)
{
$this->shippingCostsService = $shippingCostsService;
$this->ianeoBusinessExtensionService = $ianeoBusinessExtensionService;
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
'product.search.result.loaded' => 'onProductLoaded'
];
}
public function onProductLoaded(EntitySearchResultLoadedEvent $event){
/** @var ProductCollection $products */
$products = $event->getResult()->getEntities();
try {
$salesChannelId = $event->getContext()->getSource()->getSalesChannelId();
} catch (\Throwable $t ) {
$salesChannelId = IaneoDefaults::SALES_CHANNEL_BAUMARKT; // TODO-NGS: find better solution, this is only hotfix
$this->logger->info('Unable to access salesChannelId - choose default SalesChanelId Baumarkt: ' . $t->getMessage());
}
if($products === null){
return;
}
if($event->getName() !== 'product.search.result.loaded'){
return;
}
// Collect shipping costs
$shippingCosts = $this->shippingCostsService->checkShippingCosts($products, $salesChannelId);
// add shipping costs flags to product extension
$this->ianeoBusinessExtensionService->addAttributes($products, $shippingCosts, 'shippingCosts');
}
}