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 ObjectManager $userManager;
  22.     private string $userClass;
  23.     public function __construct(ObjectManager $userManagerstring $userClass)
  24.     {
  25.         $this->userManager $userManager;
  26.         $this->userClass $userClass;
  27.     }
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
  32.             UserEvents::SECURITY_IMPLICIT_LOGIN => 'onImplicitLogin',
  33.         ];
  34.     }
  35.     public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
  36.     {
  37.         $this->updateUserLastLogin($event->getAuthenticationToken()->getUser());
  38.     }
  39.     public function onImplicitLogin(UserEvent $event)
  40.     {
  41.         $this->updateUserLastLogin($event->getUser());
  42.     }
  43.     private function updateUserLastLogin($user): void
  44.     {
  45.         if (!$user instanceof $this->userClass) {
  46.             return;
  47.         }
  48.         if (!$user instanceof UserInterface) {
  49.             throw new \UnexpectedValueException('In order to use this subscriber, your class has to implement UserInterface');
  50.         }
  51.         $user->setLastLogin(new \DateTime());
  52.         $this->userManager->persist($user);
  53.         $this->userManager->flush();
  54.     }
  55. }