<?php
declare(strict_types=1);
namespace VioRepresentativeLogin\Core\Checkout\Cart\Subscriber;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use VioRepresentativeLogin\Core\Checkout\Cart\Event\CheckoutAgentOrderPlacedEvent;
use VioRepresentativeLogin\Entity\Agent\AgentEntity;
use VioRepresentativeLogin\VioRepresentativeLogin;
class OrderPlacedSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $agentRepository;
private EventDispatcherInterface $eventDispatcher;
public function __construct(
EntityRepositoryInterface $agentRepository,
EventDispatcherInterface $eventDispatcher
)
{
$this->agentRepository = $agentRepository;
$this->eventDispatcher = $eventDispatcher;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'onOrderPlaced'
];
}
public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
// when the order has an employee
$orderCustomFields = $event->getOrder()->getCustomFields();
if (is_array($orderCustomFields)
&& array_key_exists(VioRepresentativeLogin::AGENT_FIELD, $orderCustomFields)) {
// load Employee
$agentId = $orderCustomFields[VioRepresentativeLogin::AGENT_FIELD];
$agent = $this->agentRepository->search((new Criteria([$agentId]))->addAssociation('salutation'), $event->getContext())->first();
if ($agent instanceof AgentEntity) {
$event->getOrder()->addExtension('agent', $agent);
$this->eventDispatcher->dispatch(new CheckoutAgentOrderPlacedEvent(
$event->getContext(),
$event->getOrder(),
$agent,
$event->getSalesChannelId()
));
}
}
}
}