vendor/sonata-project/user-bundle/src/Security/UserProvider.php line 23

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the Sonata Project package.
  5.  *
  6.  * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Sonata\UserBundle\Security;
  12. use Sonata\UserBundle\Model\UserInterface;
  13. use Sonata\UserBundle\Model\UserManagerInterface;
  14. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  15. use Symfony\Component\Security\Core\Exception\UserNotFoundException;
  16. use Symfony\Component\Security\Core\User\UserInterface as SecurityUserInterface;
  17. use Symfony\Component\Security\Core\User\UserProviderInterface;
  18. final class UserProvider implements UserProviderInterface
  19. {
  20.     public function __construct(private UserManagerInterface $userManager)
  21.     {
  22.     }
  23.     /**
  24.      * @param string $username
  25.      */
  26.     public function loadUserByUsername($username): SecurityUserInterface
  27.     {
  28.         return $this->loadUserByIdentifier($username);
  29.     }
  30.     public function loadUserByIdentifier(string $identifier): SecurityUserInterface
  31.     {
  32.         $user $this->findUser($identifier);
  33.         if (null === $user || !$user->isEnabled()) {
  34.             throw new UserNotFoundException(sprintf('Username "%s" does not exist.'$identifier));
  35.         }
  36.         return $user;
  37.     }
  38.     public function refreshUser(SecurityUserInterface $user): SecurityUserInterface
  39.     {
  40.         if (!$user instanceof UserInterface) {
  41.             throw new UnsupportedUserException(sprintf('Expected an instance of %s, but got "%s".'UserInterface::class, $user::class));
  42.         }
  43.         if (!$this->supportsClass($user::class)) {
  44.             throw new UnsupportedUserException(sprintf('Expected an instance of %s, but got "%s".'$this->userManager->getClass(), $user::class));
  45.         }
  46.         if (null === $reloadedUser $this->userManager->findOneBy(['id' => $user->getId()])) {
  47.             throw new UserNotFoundException(sprintf('User with ID "%s" could not be reloaded.'$user->getId() ?? ''));
  48.         }
  49.         return $reloadedUser;
  50.     }
  51.     /**
  52.      * @param string $class
  53.      */
  54.     public function supportsClass($class): bool
  55.     {
  56.         $userClass $this->userManager->getClass();
  57.         return $userClass === $class || is_subclass_of($class$userClass);
  58.     }
  59.     private function findUser(string $username): ?UserInterface
  60.     {
  61.         return $this->userManager->findUserByUsernameOrEmail($username);
  62.     }
  63. }