UserProvider.php 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /*
  3. * This file is part of the FOSUserBundle package.
  4. *
  5. * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace FOS\UserBundle\Security;
  11. use Symfony\Component\Security\Core\User\UserProviderInterface;
  12. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  13. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  14. use Symfony\Component\Security\Core\User\UserInterface as SecurityUserInterface;
  15. use FOS\UserBundle\Model\User;
  16. use FOS\UserBundle\Model\UserInterface;
  17. use FOS\UserBundle\Model\UserManagerInterface;
  18. use FOS\UserBundle\Propel\User as PropelUser;
  19. class UserProvider implements UserProviderInterface
  20. {
  21. /**
  22. * @var UserManagerInterface
  23. */
  24. protected $userManager;
  25. /**
  26. * Constructor.
  27. *
  28. * @param UserManagerInterface $userManager
  29. */
  30. public function __construct(UserManagerInterface $userManager)
  31. {
  32. $this->userManager = $userManager;
  33. }
  34. /**
  35. * {@inheritDoc}
  36. */
  37. public function loadUserByUsername($username)
  38. {
  39. $user = $this->findUser($username);
  40. if (!$user) {
  41. throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
  42. }
  43. return $user;
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function refreshUser(SecurityUserInterface $user)
  49. {
  50. if (!$user instanceof User && !$user instanceof PropelUser) {
  51. throw new UnsupportedUserException(sprintf('Expected an instance of FOS\UserBundle\Model\User, but got "%s".', get_class($user)));
  52. }
  53. if (null === $reloadedUser = $this->userManager->findUserBy(array('id' => $user->getId()))) {
  54. throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $user->getId()));
  55. }
  56. return $reloadedUser;
  57. }
  58. /**
  59. * {@inheritDoc}
  60. */
  61. public function supportsClass($class)
  62. {
  63. $userClass = $this->userManager->getClass();
  64. return $userClass === $class || is_subclass_of($class, $userClass);
  65. }
  66. /**
  67. * Finds a user by username.
  68. *
  69. * This method is meant to be an extension point for child classes.
  70. *
  71. * @param string $username
  72. *
  73. * @return UserInterface|null
  74. */
  75. protected function findUser($username)
  76. {
  77. return $this->userManager->findUserByUsername($username);
  78. }
  79. }