src/Events/InjectUserSubscriber.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Events;
  3. use App\Entity\UserTokenInterface;
  4. use ReflectionException;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use ApiPlatform\Core\EventListener\EventPriorities;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. class InjectUserSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var Security
  16.      */
  17.     private $security;
  18.     /**
  19.      * @var EntityManagerInterface
  20.      */
  21.     private $manager;
  22.     public function __construct(Security $securityEntityManagerInterface $manager)
  23.     {
  24.         $this->security $security;
  25.         $this->manager  $manager;
  26.     }
  27.     /**
  28.      * @param ViewEvent $event
  29.      * @return void
  30.      * @throws ReflectionException
  31.      */
  32.     public function setUser(ViewEvent $event)
  33.     {
  34.         $object $event->getControllerResult();
  35.         if (($object) && (!is_array($object)) && ($event->getRequest()->isMethod(Request::METHOD_POST))) {
  36.             $reflectionClass = new \ReflectionClass($object);
  37.             if ($reflectionClass->implementsInterface(UserTokenInterface::class) && $object->getId() === null) {
  38.                 $uniqRelation $object->setUserToken($this->security->getUser());
  39.                 if ($uniqRelation !== null) {
  40.                     $parentMethod 'get' ucfirst($uniqRelation['parent_name']);
  41.                     $old_object $this->manager->getRepository(get_class($object))->findOneBy([
  42.                         $uniqRelation['property_name'] => $this->security->getUser(),
  43.                         $uniqRelation['parent_name']   => $object->$parentMethod()
  44.                     ]);
  45.                     if ($old_object) {
  46.                         $this->manager->remove($old_object);
  47.                     }
  48.                 }
  49.             }
  50.         }
  51.     }
  52.     /**
  53.      * @return array<string, mixed>
  54.      */
  55.     public static function getSubscribedEvents(): array
  56.     {
  57.         return [
  58.             KernelEvents::VIEW => ['setUser'EventPriorities::PRE_WRITE,]
  59.         ];
  60.     }
  61. }