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

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. /**
  19. * @phpstan-implements UserProviderInterface<UserInterface>
  20. */
  21. final class UserProvider implements UserProviderInterface
  22. {
  23. public function __construct(private UserManagerInterface $userManager)
  24. {
  25. }
  26. /**
  27. * @param string $username
  28. */
  29. public function loadUserByUsername($username): SecurityUserInterface
  30. {
  31. return $this->loadUserByIdentifier($username);
  32. }
  33. public function loadUserByIdentifier(string $identifier): SecurityUserInterface
  34. {
  35. $user = $this->findUser($identifier);
  36. if (null === $user || !$user->isEnabled()) {
  37. throw new UserNotFoundException(\sprintf('Username "%s" does not exist.', $identifier));
  38. }
  39. return $user;
  40. }
  41. public function refreshUser(SecurityUserInterface $user): SecurityUserInterface
  42. {
  43. if (!$user instanceof UserInterface) {
  44. throw new UnsupportedUserException(\sprintf('Expected an instance of %s, but got "%s".', UserInterface::class, $user::class));
  45. }
  46. if (!$this->supportsClass($user::class)) {
  47. throw new UnsupportedUserException(\sprintf('Expected an instance of %s, but got "%s".', $this->userManager->getClass(), $user::class));
  48. }
  49. if (null === $reloadedUser = $this->userManager->findOneBy(['id' => $user->getId()])) {
  50. throw new UserNotFoundException(\sprintf('User with ID "%s" could not be reloaded.', $user->getId() ?? ''));
  51. }
  52. return $reloadedUser;
  53. }
  54. /**
  55. * @param string $class
  56. */
  57. public function supportsClass($class): bool
  58. {
  59. $userClass = $this->userManager->getClass();
  60. return $userClass === $class || is_subclass_of($class, $userClass);
  61. }
  62. private function findUser(string $username): ?UserInterface
  63. {
  64. return $this->userManager->findUserByUsernameOrEmail($username);
  65. }
  66. }