<?php declare(strict_types=1);
namespace Swpa\SwpaSort\Subscriber;
use Shopware\Core\Content\Product\Events\ProductIndexerEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
use Shopware\Elasticsearch\Framework\Indexing\ElasticsearchIndexer;
use Swpa\SwpaSort\Service\CatalogRepositoryInterface;
use Swpa\SwpaSort\Service\Indexing\SwpaSortingMessage;
use Swpa\SwpaSort\Service\SwpaSortingContextSource;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\MessageBusInterface;
class ProductUpdater implements EventSubscriberInterface
{
private ElasticsearchIndexer $indexer;
private EntityDefinition $definition;
private MessageBusInterface $messageBus;
private CatalogRepositoryInterface $catalogRepository;
private bool $elasticsearchEnabled;
/**
* @internal
*/
public function __construct(
ElasticsearchIndexer $indexer,
EntityDefinition $definition,
MessageBusInterface $messageBus,
CatalogRepositoryInterface $catalogRepository,
bool $elasticSearchEnabled
)
{
$this->indexer = $indexer;
$this->definition = $definition;
$this->messageBus = $messageBus;
$this->catalogRepository = $catalogRepository;
$this->elasticsearchEnabled = $elasticSearchEnabled;
}
public static function getSubscribedEvents()
{
return [
ProductIndexerEvent::class => ['update', -1],
];
}
public function update(ProductIndexerEvent $event): void
{
if ($this->elasticsearchEnabled && $event->getContext()->getSource() instanceof SwpaSortingContextSource) {
$productIds = $event->getIds();
$productIds = array_unique($productIds);
$message = new SwpaSortingMessage($productIds, null);
$message->setIndexer('swpa.sort.product.indexer');
$this->messageBus->dispatch($message);
if ($children = $this->catalogRepository->fetchChildrenByProductIds($productIds)) {
$this->indexer->updateIds($this->definition, $children);
}
}
}
}