vendor/sylius/sylius/src/Sylius/Bundle/UserBundle/EventListener/UserLastLoginSubscriber.php line 49

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\UserBundle\EventListener;
  12. use Doctrine\Persistence\ObjectManager;
  13. use Sylius\Bundle\UserBundle\Event\UserEvent;
  14. use Sylius\Bundle\UserBundle\UserEvents;
  15. use Sylius\Component\User\Model\UserInterface;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  18. use Symfony\Component\Security\Http\SecurityEvents;
  19. final class UserLastLoginSubscriber implements EventSubscriberInterface
  20. {
  21.     private ?\DateInterval $trackInterval;
  22.     public function __construct(
  23.         private ObjectManager $userManager,
  24.         private string $userClass,
  25.         ?string $trackInterval,
  26.     ) {
  27.         $this->trackInterval null === $trackInterval null : new \DateInterval($trackInterval);
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
  33.             UserEvents::SECURITY_IMPLICIT_LOGIN => 'onImplicitLogin',
  34.         ];
  35.     }
  36.     public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
  37.     {
  38.         $this->updateUserLastLogin($event->getAuthenticationToken()->getUser());
  39.     }
  40.     public function onImplicitLogin(UserEvent $event)
  41.     {
  42.         $this->updateUserLastLogin($event->getUser());
  43.     }
  44.     private function updateUserLastLogin(mixed $user): void
  45.     {
  46.         if (!$this->shouldUserBeUpdated($user)) {
  47.             return;
  48.         }
  49.         $user->setLastLogin(new \DateTime());
  50.         $this->userManager->persist($user);
  51.         $this->userManager->flush();
  52.     }
  53.     private function shouldUserBeUpdated(mixed $user): bool
  54.     {
  55.         if (!$user instanceof $this->userClass) {
  56.             return false;
  57.         }
  58.         if (!$user instanceof UserInterface) {
  59.             throw new \UnexpectedValueException('In order to use this subscriber, your class has to implement UserInterface');
  60.         }
  61.         if (null === $this->trackInterval || null === $user->getLastLogin()) {
  62.             return true;
  63.         }
  64.         return $user->getLastLogin() <= (new \DateTime())->sub($this->trackInterval);
  65.     }
  66. }