src/EventSubscriber/StockSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\ProductIn;
  5. use App\Entity\ProductOut;
  6. use App\Entity\User;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\RequestEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\HttpKernel\Event\ViewEvent;
  13. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  14. class StockSubscriber implements EventSubscriberInterface
  15. {/**
  16.  * @var TokenStorageInterface
  17.  */
  18.     private TokenStorageInterface $tokenStorage;
  19.     private EntityManagerInterface $entityManager;
  20.     public function __construct(TokenStorageInterface $tokenStorageEntityManagerInterface $em)
  21.     {
  22.         $this->tokenStorage $tokenStorage;
  23.         $this->entityManager $em;
  24.     }
  25.     public function onRequestEvent(ViewEvent $event)
  26.     {
  27.         //return;
  28.         // ...
  29.         //$test = $event->getRequest()->attributes->get('data');
  30.         //$prevData = $event->getRequest()->attributes->get('previous_data');
  31.         $method $event->getRequest()->getMethod();
  32.         $result $event->getControllerResult();
  33.         /** @var $user User */
  34.         $user $this->tokenStorage->getToken()->getUser();
  35.         /*if (!$result instanceof ProductOut || Request::METHOD_POST !== $method) {
  36.             return;
  37.         }else{
  38.         }*/
  39.         if ($result instanceof ProductOut || $result instanceof ProductIn){
  40.             //API call POST
  41.             if (Request::METHOD_POST === $method){
  42.                 $result->setUser($user);
  43.                 $this->entityManager->flush();
  44.             }
  45. /*            if ($result instanceof ProductOut){
  46.                 //deduct from the inventory
  47.                 $product = $result->getProduct();
  48.                 $qty = $product->getQty() - $result->getQty();
  49.                 if ($qty > 0){
  50.                 }
  51.             }*/
  52.         }
  53.         //return;
  54.     }
  55.     public static function getSubscribedEvents(): array
  56.     {
  57.         return [
  58.             //RequestEvent::class => 'onRequestEvent',
  59.             KernelEvents::VIEW => ['onRequestEvent'EventPriorities::POST_WRITE],
  60.         ];
  61.     }
  62. }