<?php
namespace CioPaymentMethodCostcenter\Subscriber;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class CheckoutSubscriber implements EventSubscriberInterface
{
private ?Request $request;
private EntityRepositoryInterface $orderRepository;
public function __construct(RequestStack $requestStack, EntityRepositoryInterface $orderRepository)
{
$this->request = $requestStack->getCurrentRequest();
$this->orderRepository = $orderRepository;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlacedEvent'
];
}
public function onCheckoutOrderPlacedEvent(CheckoutOrderPlacedEvent $event)
{
$customFields = [];
if ($currentCustomFields = $event->getOrder()->getCustomFields()) {
if (is_array($currentCustomFields)) {
$customFields = $currentCustomFields;
}
}
if ($this->request) {
$customFields = array_merge($customFields, [
'cio_costcenter' => $this->request->request->get('cio_costcenter')
]);
}
$event->getOrder()->setCustomFields($customFields);
try {
$this->orderRepository->update([
[
'id' => $event->getOrder()->getId(),
'customFields' => $customFields
]
], $event->getContext());
} catch (\Throwable $e) {
}
}
}