<?php declare(strict_types=1);
namespace GlobusSW6\Subscriber;
use GlobusSW6\Core\Content\Warranty\WarrantyEntity;
use GlobusSW6\Service\IaneoBusinessExtension;
use GlobusSW6\Service\WarrantyService;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\Api\Context\SystemSource;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
class WarrantySubscriber implements EventSubscriberInterface
{
/** @var WarrantyService */
private $warrantyService;
/** @var IaneoBusinessExtension */
private $ianeoBusinessExtension;
/**
* WarrantySubscriber constructor.
* @param WarrantyService $warrantyService
* @param IaneoBusinessExtension $ianeoBusinessExtension
*/
public function __construct(WarrantyService $warrantyService, IaneoBusinessExtension $ianeoBusinessExtension)
{
$this->warrantyService = $warrantyService;
$this->ianeoBusinessExtension = $ianeoBusinessExtension;
}
public static function getSubscribedEvents()
{
return [
'product.search.result.loaded' => ['onProduct', 1000]
];
}
public function onProduct(EntitySearchResultLoadedEvent $event)
{
// do not fire event in backend context
if ($event->getContext()->getSource() instanceof AdminApiSource) {
if ($event->getContext()->getSource()->isAdmin()) {
return;
}
}
if ($event->getContext()->getSource() instanceof SystemSource) {
return;
}
$products = $event->getResult()->getElements();
if (empty($products)) {
return;
}
// detect warranties
$warranties = $this->warrantyService->checkWarranty($event->getResult()->getEntities(), $event->getContext()->getSource()->getSalesChannelId());
foreach ($products as $product) {
/** @var ProductEntity $product */
/** @var array $productExtensions */
$productExtensions = $product->getExtensions();
if (!array_key_exists('ianeoExtensions', $productExtensions)) {
continue;
}
/** @var ArrayStruct $ianeoExtensions */
$ianeoExtensions = $productExtensions['ianeoExtensions'];
// in case product has warranties, remove potential additionalServiceSets
if (array_key_exists($product->getId(), $warranties)) {
if ($ianeoExtensions->has('additionalServiceSets') && ($ianeoExtensions['additionalServiceSets'] !== null)) {
unset($ianeoExtensions['additionalServiceSets']);
}
}
}
// add warranties to products
$this->ianeoBusinessExtension->addAttributes($event->getResult()->getEntities(), $warranties, 'warranty');
}
}