<?php declare(strict_types=1);
namespace Swag\EnterpriseSearch\Boosting\DataAbstractionLayer;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\DeleteCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\WriteCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
use Shopware\Core\Framework\Uuid\Uuid;
use Swag\EnterpriseSearch\Boosting\BoostingDefinition;
use Swag\EnterpriseSearch\Boosting\BoostingEntity;
use Swag\EnterpriseSearch\Boosting\EntityStream\Service\EntityStreamResolver;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BoostingDeletionSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $entityStreamRepository;
/**
* @var EntityRepositoryInterface
*/
private $boostingRepository;
public function __construct(
EntityRepositoryInterface $entityStreamRepository,
EntityRepositoryInterface $boostingRepository
) {
$this->entityStreamRepository = $entityStreamRepository;
$this->boostingRepository = $boostingRepository;
}
public static function getSubscribedEvents(): array
{
return [
PreWriteValidationEvent::class => 'checkAndDeleteEntityStream',
];
}
public function checkAndDeleteEntityStream(PreWriteValidationEvent $preWriteValidationEvent): void
{
$commands = $preWriteValidationEvent->getCommands();
$boostingIds = $this->getBoostingIdsFromDeleteCommands($commands);
if (!$boostingIds) {
return;
}
$boostingIds = Uuid::fromBytesToHexList($boostingIds);
$idsToDelete = $this->getEntityStreamIdsFromBoostingIds($boostingIds, $preWriteValidationEvent);
if (!$idsToDelete) {
return;
}
$this->entityStreamRepository->delete($idsToDelete, $preWriteValidationEvent->getContext());
}
/**
* @param WriteCommand[] $commands
*/
private function getBoostingIdsFromDeleteCommands(array $commands): array
{
$boostingIds = [];
foreach ($commands as $command) {
if (!$command instanceof DeleteCommand) {
continue;
}
if (!$command->getDefinition() instanceof BoostingDefinition) {
continue;
}
$boostingIds = array_merge($command->getPrimaryKey(), $boostingIds);
}
return $boostingIds;
}
/**
* @param string[] $boostingIds
*/
private function getEntityStreamIdsFromBoostingIds(
array $boostingIds,
PreWriteValidationEvent $preWriteValidationEvent
): array {
$criteria = new Criteria($boostingIds);
$boostingCollection = $this->boostingRepository->search($criteria, $preWriteValidationEvent->getContext());
$idsToDelete = [];
/** @var BoostingEntity $boosting */
foreach ($boostingCollection->getElements() as $boosting) {
if ($boosting->getType() !== EntityStreamResolver::TYPE) {
continue;
}
$idsToDelete[] = ['id' => $boosting->getTypeId()];
}
return $idsToDelete;
}
}