<?php declare(strict_types=1);
namespace Jlau\LoginAsCustomer\Subscriber;
use Jlau\LoginAsCustomer\Controller\LoginAsCustomer;
use Jlau\LoginAsCustomer\LoginAsCustomer\LoginAsCustomerEntity;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
class CheckoutOrderPlaced implements EventSubscriberInterface
{
private RequestStack $requestStack;
private EntityRepositoryInterface $orderRepository;
public function __construct(RequestStack $requestStack, EntityRepositoryInterface $orderRepository)
{
$this->requestStack = $requestStack;
$this->orderRepository = $orderRepository;
}
public static function getSubscribedEvents()
{
return [CheckoutOrderPlacedEvent::class => 'blameLoggedInUserForOrder'];
}
public function blameLoggedInUserForOrder(CheckoutOrderPlacedEvent $event)
{
try {
$session = $this->requestStack->getSession();
} catch (SessionNotFoundException $e) {
return;
}
if (!$session->has(LoginAsCustomer::SESSION_NAME)) {
return;
}
/** @var LoginAsCustomerEntity $loginAsCustomer */
$loginAsCustomer = $session->get(LoginAsCustomer::SESSION_NAME);
$orderId = $event->getOrderId();
$customFields = $event->getOrder()->getCustomFields();
$customFields['login-as-customer-user'] = $loginAsCustomer->getUserId();
$order = [[
'id' => $orderId,
'customFields' => $customFields
]];
$this->orderRepository->update($order, $event->getContext());
}
}