<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\AccountHistory;
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;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AccountSubscriber implements EventSubscriberInterface
{
private $tokentStorage;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $entityManager)
{
$this->tokentStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
['updateAccountAmount', EventPriorities::PRE_WRITE],
['setCreatedBy', EventPriorities::PRE_WRITE],
],
];
}
public function updateAccountAmount(ViewEvent $event){
$accoutHistory = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$accoutHistory instanceof AccountHistory || Request::METHOD_POST !== $method) {
return;
}
$accoutHistory->getAccount()->setAmount($accoutHistory->getAccount()->getAmount() + $accoutHistory->getAmount());
}
public function setCreatedBy(ViewEvent $event){
$accoutHistory = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$accoutHistory instanceof AccountHistory || Request::METHOD_POST !== $method) {
return;
}
$accoutHistory->setCreatedBy($this->tokentStorage->getToken()->getUser());
}
}