<?php
declare(strict_types=1);
namespace VioB2BLogin\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 VioB2BLogin\Core\Checkout\Cart\Event\CheckoutEmployeeOrderPlacedEvent;
use VioB2BLogin\Entity\Employee\EmployeeEntity;
use VioB2BLogin\VioB2BLogin;
class OrderPlacedSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $employeeRepository;
private EventDispatcherInterface $eventDispatcher;
public function __construct(
EntityRepositoryInterface $employeeRepository,
EventDispatcherInterface $eventDispatcher
)
{
$this->employeeRepository = $employeeRepository;
$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(VioB2BLogin::EMPLOYEE_FIELD, $orderCustomFields)) {
// load Employee
$employeeId = $orderCustomFields[VioB2BLogin::EMPLOYEE_FIELD];
$criteria = new Criteria([$employeeId]);
$criteria->addAssociation('salutation')
->addAssociation('customer.salutation');
$employee = $this->employeeRepository->search($criteria, $event->getContext())->first();
if ($employee instanceof EmployeeEntity) {
$event->getOrder()->addExtension('employee', $employee);
$this->eventDispatcher->dispatch(new CheckoutEmployeeOrderPlacedEvent(
$event->getContext(),
$event->getOrder(),
$employee,
$event->getSalesChannelId()
));
}
}
}
}