<?php
namespace Abas\AbasConnector\Subscribers\Order;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Checkout\Cart\Order\Transformer\DeliveryTransformer;
use Shopware\Core\Checkout\Cart\Order\Transformer\LineItemTransformer;
use Shopware\Core\Checkout\Order\Aggregate\OrderDelivery\OrderDeliveryStates;
use Shopware\Core\System\StateMachine\StateMachineRegistry;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use UnexpectedValueException;
class TransformAddressSubcriber implements EventSubscriberInterface
{
/**
* @var StateMachineRegistry
*/
private $stateMachineRegistry;
/**
* @param StateMachineRegistry $stateMachineRegistry
*/
public function __construct(StateMachineRegistry $stateMachineRegistry)
{
$this->stateMachineRegistry = $stateMachineRegistry;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
CartConvertedEvent::class => 'addAddressCustomFields'
];
}
/**
* @param CartConvertedEvent $event
*
* @return void
* @throws UnexpectedValueException
*/
public function addAddressCustomFields(CartConvertedEvent $event): void
{
$cart = $event->getCart();
$data = $event->getConvertedCart();
$conversionContext = $event->getConversionContext();
$convertedLineItems = LineItemTransformer::transformCollection($cart->getLineItems());
$shippingAddresses = [];
if ($conversionContext->shouldIncludeDeliveries()) {
$shippingAddresses = AddressTransformer::transformCollection($cart->getDeliveries()->getAddresses(), true);
$context = $event->getContext();
$data['deliveries'] = DeliveryTransformer::transformCollection(
$cart->getDeliveries(),
$convertedLineItems,
$this->stateMachineRegistry->getInitialState(
OrderDeliveryStates::STATE_MACHINE,
$context
)->getId(),
$context,
$shippingAddresses
);
}
if ($conversionContext->shouldIncludeBillingAddress()) {
$customer = $event->getSalesChannelContext()->getCustomer();
if ($customer === null) {
throw new UnexpectedValueException('customer is not available.');
}
$activeBillingAddress = $customer->getActiveBillingAddress();
if ($activeBillingAddress === null) {
throw new UnexpectedValueException('active billing address is not available.');
}
$customerAddressId = $activeBillingAddress->getId();
if (array_key_exists($customerAddressId, $shippingAddresses)) {
$billingAddressId = $shippingAddresses[$customerAddressId]['id'];
} else {
$billingAddress = AddressTransformer::transform($activeBillingAddress);
$data['addresses'] = [$billingAddress];
$billingAddressId = $billingAddress['id'];
}
$data['billingAddressId'] = $billingAddressId;
}
$data['lineItems'] = array_values($convertedLineItems);
$event->setConvertedCart($data);
}
}