<?php
declare(strict_types=1);
namespace Wbfk\MultipleDeliveries\Subscriber;
use Shopware\Core\Checkout\Cart\Delivery\Struct\Delivery;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Checkout\Cart\Order\IdStruct;
use Shopware\Core\Checkout\Cart\Order\OrderConverter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CartConvertedSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CartConvertedEvent::class => 'restoreOrderDeliveryState',
];
}
public function restoreOrderDeliveryState(CartConvertedEvent $event): void
{
$convertedCart = $event->getConvertedCart();
$cart = $event->getCart();
foreach ($cart->getDeliveries() as $delivery) {
/** @var Delivery $delivery */
/** @var ?IdStruct $originalStateIdStruct */
$originalStateIdStruct = $delivery->getExtension('originalStateId');
if (!$originalStateIdStruct) {
continue;
}
/** @var ?IdStruct $originalIdStruct */
$originalIdStruct = $delivery->getExtension(OrderConverter::ORIGINAL_ID);
if (!($originalIdStruct instanceof IdStruct)) {
continue;
}
foreach ($convertedCart['deliveries'] as $key => $convertedDelivery) {
if ($convertedDelivery['id'] == $originalIdStruct->getId()) {
$convertedCart['deliveries'][$key]['stateId'] = $originalStateIdStruct->getId();
break;
}
}
}
$event->setConvertedCart($convertedCart);
}
}