src/EventSubscriber/EntitySubscriber.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use App\Entity\User;
  5. use App\Service\UserService;
  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\Security;
  11. final class EntitySubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         protected Security $security,
  15.         protected UserService $userService
  16.     ) {}
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => [
  21.                 ['userRegister'EventPriorities::PRE_WRITE],
  22.             ],
  23.         ];
  24.     }
  25.     public function addCreatedBy(ViewEvent $httpEvent): void
  26.     {
  27.         $entity $httpEvent->getControllerResult();
  28.         $method $httpEvent->getRequest()->getMethod();
  29.         if (Request::METHOD_POST !== $method) {
  30.             return;
  31.         }
  32.         $user $this->security->getUser();
  33.         if (!$user || !property_exists($entity'createdBy')) {
  34.             return;
  35.         }
  36.         $rp = new \ReflectionProperty($entity'createdBy');
  37.         $type $rp->getType()->getName();
  38.         if ($type === User::class) {
  39.             $entity->createdBy $user;
  40.         }
  41.     }
  42.     public function userRegister(ViewEvent $httpEvent): void
  43.     {
  44.         $user $httpEvent->getControllerResult();
  45.         $method $httpEvent->getRequest()->getMethod();
  46.         if (!$user instanceof User || Request::METHOD_POST !== $method) {
  47.             return;
  48.         }
  49.         $this->userService->register($user);
  50.     }
  51. }