<?php
namespace Boldr\Shop\MultishopBundle\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface ;
use Boldr\Shop\ShopBundle\ShopContext;
use Boldr\Shop\ShopBundle\Event\{ OrderUpdatedEvent, OrderStateUpdatedEvent };
use Doctrine\ORM\EntityManagerInterface;
use Boldr\Shop\ShopBundle\OrderFlow\OrderFlowManagerInterface;
use Boldr\Shop\MultishopBundle\Entity\OrderShop;
use Boldr\Shop\ShopBundle\Entity\Order;
use Boldr\Shop\MultishopBundle\DefaultShop\DefaultShopProviderInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class EventSubscriber implements EventSubscriberInterface
{
private OrderFlowManagerInterface $orderFlowManager;
private EntityManagerInterface $em;
private DefaultShopProviderInterface $defaultShopProvider;
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack, OrderFlowManagerInterface $orderFlowManager, EntityManagerInterface $em, DefaultShopProviderInterface $defaultShopProvider)
{
$this->requestStack = $requestStack;
$this->orderFlowManager = $orderFlowManager;
$this->em = $em;
$this->defaultShopProvider = $defaultShopProvider;
}
public static function getSubscribedEvents(): array
{
return [
OrderStateUpdatedEvent::class => ['onOrderStateUpdated'],
OrderUpdatedEvent::class => ['onOrderUpdated']
];
}
public function onOrderUpdated(OrderUpdatedEvent $event)
{
$this->addDefaultShopToOrder($event->getOrder());
}
/**
* Add default shop to orders without shop
*/
public function onOrderStateUpdated(OrderStateUpdatedEvent $event)
{
$this->addDefaultShopToOrder($event->getOrder());
}
private function addDefaultShopToOrder(Order $order)
{
$orderShop = $order->getId() === null ? null : $this->em->getRepository(OrderShop::class)->find($order);
if ($orderShop !== null)
{
return;
}
if (count($order->getItems()))
{
$request = $this->requestStack->getCurrentRequest();
$defaultShop = $this->defaultShopProvider->getDefaultShop($request, $order->getCustomer());
$orderShop = new OrderShop($order, $defaultShop);
$this->em->persist($orderShop);
$this->em->flush();
}
}
}