<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Orders;
use App\Entity\Rdv;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class OrderSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [[
'invalidateCart', EventPriorities::POST_WRITE,
],[
'setCode', EventPriorities::PRE_WRITE,
]]
];
}
public function invalidateCart(ViewEvent $event):void
{
$order = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$order instanceof Orders || Request::METHOD_POST !== $method) {
return;
}
$order->getPanier()->setState(true);
$this->em->flush();
}
public function setCode(ViewEvent $event):void
{
$order = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$order instanceof Orders || Request::METHOD_POST !== $method) {
return;
}
$code = time().''.mt_rand();
$order->setCode($code);
$order->setTransactionId($code);
$this->em->flush();
}
}