src/EventSubscriber/UserNotificacionSubscriber.php line 29

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Entity\Evento;
  5. use App\Entity\Notificacion;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use ApiPlatform\Symfony\EventListener\EventPriorities;
  11. use Symfony\Bundle\SecurityBundle\Security;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. final class UserNotificacionSubscriber implements EventSubscriberInterface
  14. {
  15.     public function __construct(private readonly EntityManagerInterface $entityManager, private readonly Security $security)
  16.     {
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             KernelEvents::VIEW => ['createNotificacion'EventPriorities::POST_WRITE],
  22.         ];
  23.     }
  24.     public function createNotificacion(ViewEvent $event): void
  25.     {
  26.         $user $this->security->getUser();
  27.         if (!$user instanceof User) {
  28.             return;
  29.         }
  30.         $newUser $event->getControllerResult();
  31.         $method $event->getRequest()->getMethod();
  32.         if (!$newUser instanceof User || Request::METHOD_POST !== $method) {
  33.             return;
  34.         }
  35.         $admins $this->entityManager->getRepository(User::class)->findBy(['empresa' => $user->getEmpresa(), 'tipo' => User::TIPO_ADMIN]);
  36.         foreach ($admins as $admin) {
  37.             $notificacion = new Notificacion();
  38.             $notificacion->setEmpresa($newUser->getEmpresa());
  39.             $notificacion->setUser($admin);
  40.             $notificacion->setTitulo('Nuevo ' $newUser->getTipo() . ' creado');
  41.             $notificacion->setIsNew(true);
  42.             $notificacion->setModulo(User::MODULO);
  43.             $notificacion->setModuloRef($newUser->getUuid());
  44.             $notificacion->setHint($newUser->getUsername());
  45.             $notificacion->setCreatedAt(new \DateTimeImmutable());
  46.             $this->entityManager->persist($notificacion);
  47.         }
  48.         $this->entityManager->flush();
  49.     }
  50. }