<?php declare(strict_types=1);
namespace Swag\EnterpriseSearch\Configuration;
use Shopware\Core\Content\Category\CategoryDefinition;
use Shopware\Core\Content\Product\Aggregate\ProductManufacturer\ProductManufacturerDefinition;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\System\SalesChannel\SalesChannelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class GatewayConfigurationCreator implements EventSubscriberInterface
{
private const MAX_SEARCH_COUNT = 10;
private const MAX_SUGGEST_COUNT = 10;
/**
* @var EntityRepositoryInterface
*/
private $entityRepository;
public function __construct(
EntityRepositoryInterface $entityRepository
) {
$this->entityRepository = $entityRepository;
}
public static function getSubscribedEvents(): array
{
return [
SalesChannelEvents::SALES_CHANNEL_WRITTEN => 'onSalesChannelWritten',
];
}
public function onSalesChannelWritten(EntityWrittenEvent $salesChannelWrittenEvent): void
{
$salesChannelWrittenResults = $salesChannelWrittenEvent->getWriteResults();
$newGatewayConfigurations = [];
foreach ($salesChannelWrittenResults as $salesChannelWrittenResult) {
if (!$this->isInsertOperation($salesChannelWrittenResult)) {
continue;
}
$newGatewayConfigurations = array_merge($this->createGatewayConfigurationsForSalesChannel($salesChannelWrittenResult), $newGatewayConfigurations);
}
if (empty($newGatewayConfigurations)) {
return;
}
$this->entityRepository->create($newGatewayConfigurations, $salesChannelWrittenEvent->getContext());
}
protected function getEntityNames(): array
{
return [
ProductDefinition::ENTITY_NAME,
ProductManufacturerDefinition::ENTITY_NAME,
CategoryDefinition::ENTITY_NAME,
];
}
private function createGatewayConfigurationsForSalesChannel(EntityWriteResult $createdSalesChannel): array
{
$entities = [];
foreach ($this->getEntityNames() as $entityName) {
$configuration = new GatewayConfigurationEntity();
$configuration->setEntityName($entityName);
$configuration->setMaxSuggestCount(self::MAX_SUGGEST_COUNT);
if ($entityName !== ProductDefinition::ENTITY_NAME) {
$configuration->setMaxSearchCount(self::MAX_SEARCH_COUNT);
}
/** @var string $salesChannelId */
$salesChannelId = $createdSalesChannel->getPrimaryKey();
$configuration->setSalesChannelId($salesChannelId);
$entities[] = $configuration->getVars();
}
return $entities;
}
private function isInsertOperation(EntityWriteResult $entityWriteResult): bool
{
return $entityWriteResult->getOperation() === EntityWriteResult::OPERATION_INSERT;
}
}