custom/plugins/CioPaymentMethodCostcenter/src/Subscriber/CheckoutSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace CioPaymentMethodCostcenter\Subscriber;
  3. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. class CheckoutSubscriber implements EventSubscriberInterface
  9. {
  10.     private ?Request $request;
  11.     private EntityRepositoryInterface $orderRepository;
  12.     public function __construct(RequestStack $requestStackEntityRepositoryInterface $orderRepository)
  13.     {
  14.         $this->request $requestStack->getCurrentRequest();
  15.         $this->orderRepository $orderRepository;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         // Return the events to listen to as array like this:  <event to listen to> => <method to execute>
  20.         return [
  21.             CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlacedEvent'
  22.         ];
  23.     }
  24.     public function onCheckoutOrderPlacedEvent(CheckoutOrderPlacedEvent $event)
  25.     {
  26.         $customFields = [];
  27.         if ($currentCustomFields $event->getOrder()->getCustomFields()) {
  28.             if (is_array($currentCustomFields)) {
  29.                 $customFields $currentCustomFields;
  30.             }
  31.         }
  32.         if ($this->request) {
  33.             $customFields array_merge($customFields, [
  34.                 'cio_costcenter' => $this->request->request->get('cio_costcenter')
  35.             ]);
  36.         }
  37.         $event->getOrder()->setCustomFields($customFields);
  38.         try {
  39.             $this->orderRepository->update([
  40.                 [
  41.                     'id' => $event->getOrder()->getId(),
  42.                     'customFields' => $customFields
  43.                 ]
  44.             ], $event->getContext());
  45.         } catch (\Throwable $e) {
  46.         }
  47.     }
  48. }