src/EventSubscriber/DocumentoNotificacionSubscriber.php line 29

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Entity\Documento;
  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\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  13. final class DocumentoNotificacionSubscriber implements EventSubscriberInterface
  14. {
  15.     public function __construct(private readonly EntityManagerInterface $entityManager, private readonly TokenStorageInterface $tokenStorage)
  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.         $token $this->tokenStorage->getToken();
  27.         if (!$token instanceof \Symfony\Component\Security\Core\Authentication\Token\TokenInterface) {
  28.             return;
  29.         }
  30.         $user $token->getUser();
  31.         if (!$user instanceof User) {
  32.             return;
  33.         }
  34.         $documento $event->getControllerResult();
  35.         $method $event->getRequest()->getMethod();
  36.         if (!$documento instanceof Documento || Request::METHOD_POST !== $method) {
  37.             return;
  38.         }
  39.         $admins $this->entityManager->getRepository(User::class)->findBy(['empresa' => $user->getEmpresa(), 'tipo' => User::TIPO_ADMIN]);
  40.         foreach ($admins as $admin) {
  41.             $notificacion = new Notificacion();
  42.             $notificacion->setEmpresa($user->getEmpresa());
  43.             $notificacion->setUser($admin);
  44.             $notificacion->setTitulo('Se ha subido un nuevo documento');
  45.             $notificacion->setIsNew(true);
  46.             $notificacion->setModulo(Documento::MODULO);
  47.             $notificacion->setModuloRef($documento->getUuid());
  48.             $notificacion->setHint($documento->getNombreArchivo());
  49.             $this->entityManager->persist($notificacion);
  50.         }
  51.         $this->entityManager->flush();
  52.     }
  53. }