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