<?php
namespace App\Events;
use App\Entity\UserTokenInterface;
use ReflectionException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class InjectUserSubscriber implements EventSubscriberInterface
{
/**
* @var Security
*/
private $security;
/**
* @var EntityManagerInterface
*/
private $manager;
public function __construct(Security $security, EntityManagerInterface $manager)
{
$this->security = $security;
$this->manager = $manager;
}
/**
* @param ViewEvent $event
* @return void
* @throws ReflectionException
*/
public function setUser(ViewEvent $event)
{
$object = $event->getControllerResult();
if (($object) && (!is_array($object)) && ($event->getRequest()->isMethod(Request::METHOD_POST))) {
$reflectionClass = new \ReflectionClass($object);
if ($reflectionClass->implementsInterface(UserTokenInterface::class) && $object->getId() === null) {
$uniqRelation = $object->setUserToken($this->security->getUser());
if ($uniqRelation !== null) {
$parentMethod = 'get' . ucfirst($uniqRelation['parent_name']);
$old_object = $this->manager->getRepository(get_class($object))->findOneBy([
$uniqRelation['property_name'] => $this->security->getUser(),
$uniqRelation['parent_name'] => $object->$parentMethod()
]);
if ($old_object) {
$this->manager->remove($old_object);
}
}
}
}
}
/**
* @return array<string, mixed>
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['setUser', EventPriorities::PRE_WRITE,]
];
}
}