<?php declare(strict_types=1);
namespace NrbnSenertec\Subscriber;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
use Shopware\Core\System\SalesChannel\SalesChannel\AbstractContextSwitchRoute;
use Shopware\Core\Checkout\Customer\SalesChannel\AccountService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PaymentAndShippingAddressSubscriber implements EventSubscriberInterface{
private EntityRepository $customerRepository;
private AccountService $accountService;
private AbstractContextSwitchRoute $salesChannelContextSwitcher;
public function __construct(
EntityRepository $customerRepository,
AccountService $accountService,
AbstractContextSwitchRoute $salesChannelContextSwitcher
) {
$this->customerRepository = $customerRepository;
$this->accountService = $accountService;
$this->salesChannelContextSwitcher = $salesChannelContextSwitcher;
}
public static function getSubscribedEvents(): array {
return [
CartConvertedEvent::class => 'ChangePaymentAndShippingToStandard',
];
}
public function ChangePaymentAndShippingToStandard(CartConvertedEvent $event): void
{
$data = new RequestDataBag();
$data->set("shippingMethodId", "9744837b0bc04b6fbb2207351a959240");
$this->salesChannelContextSwitcher->switchContext($data, $event->getSalesChannelContext());
$customer = $event->getSalesChannelContext()->getCustomer();
$this->customerRepository->update([[
"id" => $customer->getId(),
"customFields" => [
"activeShippingAddress" => $customer->getDefaultShippingAddress(),
"activeShippingAddressId" => $customer->getDefaultShippingAddressId(),
]
]], $event->getContext());
}
}