<?php declare(strict_types=1);
namespace Nd\Srs\Subscriber;
use DateTime;
use Nd\Coef\Service\ProductManufacturerUrlService;
use Shopware\Core\Content\Product\Aggregate\ProductMedia\ProductMediaEntity;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Content\Product\SalesChannel\Detail\ProductConfiguratorLoader;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Entity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
class AddProductGroupData implements EventSubscriberInterface
{
private EventDispatcherInterface $dispatcher;
private EntityRepository $productRepository;
private array $results;
private bool $isLoading;
public function __construct( EventDispatcherInterface $dispatcher, EntityRepository $productRepository)
{
$this->dispatcher = $dispatcher;
$this->productRepository = $productRepository;
$this->results = [];
$this->isLoading = false;
}
public static function getSubscribedEvents(): array
{
// return [];
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded'
];
}
public function onProductsLoaded(EntityLoadedEvent $event): void
{
if($this->isLoading){
return;
}
/** @var ProductEntity $productEntity */
foreach ($event->getEntities() as $productEntity) {
if(in_array($productEntity->getId(), array_keys($this->results))) {
$group = $this->results[$productEntity->getId()];
}else{
$group = $this->getGroup($productEntity, $event->getContext());
$this->results[$productEntity->getId()] = $group;
}
if ($group) {
$productEntity->addExtension('productGroup', new ArrayStruct($group));
}
}
}
public function getGroup(ProductEntity $productEntity, Context $context){
if(!$productEntity->getExtension('srsExtension')){
return false;
}
$srsData = $productEntity->getExtension('srsExtension');
if(!$srsData->getBaseId()){
return false;
}
$baseId = $srsData->getBaseId();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('product.srsExtension.baseId', $baseId));
$criteria->addFilter(new EqualsFilter('product.parentId', null));
$criteria->addAssociation('srsExtension');
$criteria->addAssociation('manufacturer');
$criteria->addAssociation('media');
$criteria->addAssociation('options.group');
$criteria->addAssociation('cover');
$criteria->addAssociation('properties.group');
$this->isLoading = true;
$products = $this->productRepository->search($criteria, $context)->getEntities();
$this->isLoading = false;
if($products->count() < 2){
return false;
}
return [$products];
}
}