<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\ProductIn;
use App\Entity\ProductOut;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class StockSubscriber implements EventSubscriberInterface
{/**
* @var TokenStorageInterface
*/
private TokenStorageInterface $tokenStorage;
private EntityManagerInterface $entityManager;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
{
$this->tokenStorage = $tokenStorage;
$this->entityManager = $em;
}
public function onRequestEvent(ViewEvent $event)
{
//return;
// ...
//$test = $event->getRequest()->attributes->get('data');
//$prevData = $event->getRequest()->attributes->get('previous_data');
$method = $event->getRequest()->getMethod();
$result = $event->getControllerResult();
/** @var $user User */
$user = $this->tokenStorage->getToken()->getUser();
/*if (!$result instanceof ProductOut || Request::METHOD_POST !== $method) {
return;
}else{
}*/
if ($result instanceof ProductOut || $result instanceof ProductIn){
//API call POST
if (Request::METHOD_POST === $method){
$result->setUser($user);
$this->entityManager->flush();
}
/* if ($result instanceof ProductOut){
//deduct from the inventory
$product = $result->getProduct();
$qty = $product->getQty() - $result->getQty();
if ($qty > 0){
}
}*/
}
//return;
}
public static function getSubscribedEvents(): array
{
return [
//RequestEvent::class => 'onRequestEvent',
KernelEvents::VIEW => ['onRequestEvent', EventPriorities::POST_WRITE],
];
}
}