<?php declare(strict_types=1);
namespace Shopware\B2B\Order\BridgePlatform;
use Shopware\B2B\Common\IdValue;
use Shopware\B2B\Order\Framework\OrderContextService;
use Shopware\Core\Checkout\Order\OrderDefinition;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use function array_walk;
class OrderDeleteSubscriber implements EventSubscriberInterface
{
protected OrderContextService $orderContextService;
public function __construct(OrderContextService $orderContextService)
{
$this->orderContextService = $orderContextService;
}
public static function getSubscribedEvents(): array
{
return [
EntityWrittenContainerEvent::class => 'onOrderWrittenEvent',
];
}
public function onOrderWrittenEvent(EntityWrittenContainerEvent $eventContainer): void
{
$event = $eventContainer->getEventByEntityName(OrderDefinition::ENTITY_NAME);
if ($event instanceof EntityDeletedEvent) {
$this->onOrderDelete($event);
}
}
/**
* @internal
*/
protected function onOrderDelete(EntityDeletedEvent $deletedEvent): void
{
$list = [];
$writeResults = $deletedEvent->getWriteResults();
array_walk($writeResults, function (EntityWriteResult $writeResult) use (&$list) {
if ($writeResult->getOperation() === EntityWriteResult::OPERATION_DELETE) {
$payload = $writeResult->getPayload();
if (isset($payload['versionId']) && $payload['versionId'] === Defaults::LIVE_VERSION) {
$list[] = IdValue::create($writeResult->getPrimaryKey());
}
}
});
$this->orderContextService->deleteContextsByReferencedOrderIds($list);
}
}