<?php
namespace Boldr\Shop\ShopBundle\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\{ BeforeCrudActionEvent, AfterEntityUpdatedEvent };
use Boldr\Shop\ShopBundle\Entity\Order;
use Boldr\Shop\ShopBundle\Event\OrderStateUpdatedEvent;
use Psr\EventDispatcher\EventDispatcherInterface;
class OrderAdminEventSubscriber implements EventSubscriberInterface
{
private array $orderStates = [];
private EventDispatcherInterface $eventDispatcher;
public function __construct(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
public static function getSubscribedEvents()
{
return [
AfterEntityUpdatedEvent::class => [
['onAfterEntityUpdatedEvent', 10]
],
BeforeCrudActionEvent::class => [
['onBeforeCrudActionEvent', 10]
]
];
}
public function onAfterEntityUpdatedEvent(AfterEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof Order)
{
if (isset($this->orderStates[$entity->getId()]))
{
$oldOrderState = $this->orderStates[$entity->getId()];
$newOrderState = $entity->getState();
if ($oldOrderState !== $newOrderState)
{
$orderStateChangeEvent = new OrderStateUpdatedEvent($entity, $oldOrderState, $newOrderState);
$this->eventDispatcher->dispatch($orderStateChangeEvent);
}
}
}
}
public function onBeforeCrudActionEvent(BeforeCrudActionEvent $event)
{
if ($event->getAdminContext())
{
$entity = $event->getAdminContext()->getEntity()->getInstance();
if ($entity instanceof Order)
{
$this->orderStates[$entity->getId()] = $entity->getState();
}
}
}
}