3 namespace Drupal\user\EventSubscriber;
5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Drupal\Core\Session\AccountInterface;
7 use Drupal\Core\Site\Settings;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9 use Symfony\Component\HttpKernel\Event\PostResponseEvent;
10 use Symfony\Component\HttpKernel\KernelEvents;
13 * Updates the current user's last access time.
15 class UserRequestSubscriber implements EventSubscriberInterface {
18 * The current account.
20 * @var \Drupal\Core\Session\AccountInterface
27 * @var \Drupal\Core\Entity\EntityManagerInterface
29 protected $entityManager;
32 * Constructs a new UserRequestSubscriber.
34 * @param \Drupal\Core\Session\AccountInterface $account
36 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
39 public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
40 $this->account = $account;
41 $this->entityManager = $entity_manager;
45 * Updates the current user's last access time.
47 * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
48 * The event to process.
50 public function onKernelTerminate(PostResponseEvent $event) {
51 if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
52 // Do that no more than once per 180 seconds.
53 /** @var \Drupal\user\UserStorageInterface $storage */
54 $storage = $this->entityManager->getStorage('user');
55 $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
62 public static function getSubscribedEvents() {
63 // Should go before other subscribers start to write their caches. Notably
64 // before \Drupal\Core\EventSubscriber\KernelDestructionSubscriber to
65 // prevent instantiation of destructed services.
66 $events[KernelEvents::TERMINATE][] = ['onKernelTerminate', 300];