<?php declare(strict_types=1);
namespace Shopware\B2B\Order\BridgePlatform;
use Shopware\B2B\Common\IdValue;
use Shopware\B2B\Common\Repository\NotFoundException;
use Shopware\B2B\Order\Framework\OrderContext;
use Shopware\B2B\Order\Framework\OrderContextRepository;
use Shopware\Core\Checkout\Order\OrderDefinition;
use Shopware\Core\System\StateMachine\Event\StateMachineTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class OrderTransitionSubscriber implements EventSubscriberInterface
{
/**
* @var ShopOrderRepository
*/
private $shopOrderRepository;
/**
* @var OrderContextRepository
*/
private $orderContextRepository;
/**
* @var EventDispatcherInterface
*/
private $dispatcher;
public function __construct(
ShopOrderRepository $shopOrderRepository,
OrderContextRepository $orderContextRepository,
EventDispatcherInterface $dispatcher
) {
$this->shopOrderRepository = $shopOrderRepository;
$this->orderContextRepository = $orderContextRepository;
$this->dispatcher = $dispatcher;
}
public static function getSubscribedEvents()
{
return [
StateMachineTransitionEvent::class => 'onStateChange',
];
}
public function onStateChange(StateMachineTransitionEvent $event): void
{
if ($event->getEntityName() !== OrderDefinition::ENTITY_NAME) {
return;
}
try {
$orderContext = $this->updateOrderContext($event);
} catch (NotFoundException $e) {
return;
}
$this->dispatcher->dispatch(
new OrderContextStateChangedEvent(
$event->getFromPlace()->getTechnicalName(),
$event->getToPlace()->getTechnicalName(),
$orderContext
)
);
}
/**
* @internal
*/
protected function updateOrderContext(StateMachineTransitionEvent $event): OrderContext
{
$orderContext = $this->shopOrderRepository
->fetchOneOrderContextByShopOrderId(IdValue::create($event->getEntityId()));
$orderContext->status = $event->getToPlace()->getTechnicalName();
$this->orderContextRepository
->updateContext($orderContext);
return $orderContext;
}
}