src/EventSubscriber/UserActivitySubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\HttpKernel\HttpKernel;
  8. use App\Entity\User;
  9. class UserActivitySubscriber implements EventSubscriberInterface
  10. {
  11.     private $em;
  12.     private $security;
  13.     public function __construct(EntityManagerInterface $emSecurity $security)
  14.     {
  15.         $this->em $em;
  16.         $this->security $security;
  17.     }
  18.     public function onKernelController(ControllerEvent $event)
  19.     {
  20.         if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
  21.             return;
  22.         }
  23.         // Check token authentication availability
  24.         if ($this->security->getToken()) {
  25.             $user $this->security->getToken()->getUser();
  26.             
  27.             if ( ($user instanceof User)) {
  28.                 $request $event->getRequest();
  29.                 if ($request->getLocale() && $request->getLocale() != $user->getLocale()) {
  30.                     $user->setLocale($request->getLocale()=='fr'?'fr':'en');
  31.                     $this->em->flush($user);
  32.                 }
  33.                 if ( ($user instanceof User) && !($user->isActiveNow()) ) {
  34.                     $user->setLastActivityAt(new \DateTime());
  35.                     $this->em->flush($user);
  36.                 }
  37.             }
  38.         }
  39.     }
  40.     public static function getSubscribedEvents()
  41.     {
  42.         return [
  43.             'kernel.controller' => 'onKernelController',
  44.         ];
  45.     }
  46. }