<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpKernel\HttpKernel;
use App\Entity\User;
class UserActivitySubscriber implements EventSubscriberInterface
{
private $em;
private $security;
public function __construct(EntityManagerInterface $em, Security $security)
{
$this->em = $em;
$this->security = $security;
}
public function onKernelController(ControllerEvent $event)
{
if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
return;
}
// Check token authentication availability
if ($this->security->getToken()) {
$user = $this->security->getToken()->getUser();
if ( ($user instanceof User)) {
$request = $event->getRequest();
if ($request->getLocale() && $request->getLocale() != $user->getLocale()) {
$user->setLocale($request->getLocale()=='fr'?'fr':'en');
$this->em->flush($user);
}
if ( ($user instanceof User) && !($user->isActiveNow()) ) {
$user->setLastActivityAt(new \DateTime());
$this->em->flush($user);
}
}
}
}
public static function getSubscribedEvents()
{
return [
'kernel.controller' => 'onKernelController',
];
}
}