src/EventSubscriber/UserPostLogsSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Entity\UserLog;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. class UserPostLogsSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         private UrlGeneratorInterface $urlGenerator,
  15.         private TokenStorageInterface  $tokenStorage,
  16.         private EntityManagerInterface $entityManager
  17.     )
  18.     {
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             KernelEvents::CONTROLLER => 'onKernelController',
  24.         ];
  25.     }
  26.     public function onKernelController(ControllerEvent $event)
  27.     {
  28.             $user $this->tokenStorage->getToken()?->getUser();
  29.             $method =  $event->getRequest()->getMethod();
  30.             if($user instanceof User && $event->getRequest()->request && $method=='POST'){
  31.                 $currentDate = new \Datetime();
  32.                 $action $event->getRequest()->attributes->get('_controller');
  33.                 $userIp =  $event->getRequest()->getClientIp();
  34.                 $userLog = new UserLog();
  35.                 $userLog->setUser($user);
  36.                 $userLog->setIp($userIp);
  37.                 $userLog->setAction($action);
  38.                 $userLog->setMethode($method);
  39.                 $userLog->setDate($currentDate);
  40.                 if($event->getRequest()->request && $method=='POST'){
  41.                     $userLog->setData(json_encode($event->getRequest()->request->all()));
  42.                 }else{
  43.                     $userLog->setData($event->getRequest()->getPathInfo());
  44.                 }
  45.                 $this->entityManager->persist($userLog);
  46.                 $this->entityManager->flush();
  47.             }
  48.     }
  49. }