src/EventSubscriber/AccountSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\AccountHistory;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. class AccountSubscriber implements EventSubscriberInterface
  12. {
  13.     private $tokentStorage;
  14.     public function __construct(TokenStorageInterface $tokenStorageEntityManagerInterface $entityManager)
  15.     {
  16.         $this->tokentStorage $tokenStorage;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             KernelEvents::VIEW => [
  22.                 ['updateAccountAmount'EventPriorities::PRE_WRITE],
  23.                 ['setCreatedBy'EventPriorities::PRE_WRITE],
  24.             ],
  25.         ];
  26.     }
  27.     public function updateAccountAmount(ViewEvent $event){
  28.         $accoutHistory $event->getControllerResult();
  29.         $method $event->getRequest()->getMethod();
  30.         if (!$accoutHistory instanceof AccountHistory || Request::METHOD_POST !== $method) {
  31.             return;
  32.         }
  33.         $accoutHistory->getAccount()->setAmount($accoutHistory->getAccount()->getAmount() + $accoutHistory->getAmount());
  34.     }
  35.     public function setCreatedBy(ViewEvent $event){
  36.         $accoutHistory $event->getControllerResult();
  37.         $method $event->getRequest()->getMethod();
  38.         if (!$accoutHistory instanceof AccountHistory || Request::METHOD_POST !== $method) {
  39.             return;
  40.         }
  41.         $accoutHistory->setCreatedBy($this->tokentStorage->getToken()->getUser());
  42.     }
  43. }