InMemoryUserProvider.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Symfony\Component\Security\User;
  3. use Symfony\Component\Security\Exception\UsernameNotFoundException;
  4. /*
  5. * This file is part of the Symfony package.
  6. *
  7. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  8. *
  9. * For the full copyright and license information, please view the LICENSE
  10. * file that was distributed with this source code.
  11. */
  12. /**
  13. * InMemoryUserProvider is a simple non persistent user provider.
  14. *
  15. * Useful for testing, demonstration, prototyping, and for simple needs
  16. * (a backend with a unique admin for instance)
  17. *
  18. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  19. */
  20. class InMemoryUserProvider implements UserProviderInterface
  21. {
  22. protected $users;
  23. /**
  24. * Constructor.
  25. *
  26. * The user array is a hash where the keys are usernames and the values are
  27. * an array of attributes: 'password', 'enabled', and 'roles'.
  28. *
  29. * @param array $users An array of users
  30. */
  31. public function __construct(array $users = array())
  32. {
  33. foreach ($users as $username => $attributes) {
  34. $password = isset($attributes['password']) ? $attributes['password'] : null;
  35. $enabled = isset($attributes['enabled']) ? $attributes['enabled'] : true;
  36. $roles = isset($attributes['roles']) ? $attributes['roles'] : array();
  37. $user = new User($username, $password, $roles, $enabled, true, true, true);
  38. $this->createUser($user);
  39. }
  40. }
  41. /**
  42. * Adds a new User to the provider.
  43. *
  44. * @param AccountInterface $user A AccountInterface instance
  45. */
  46. public function createUser(AccountInterface $user)
  47. {
  48. if (isset($this->users[strtolower($user->getUsername())])) {
  49. throw new \LogicException('Another user with the same username already exist.');
  50. }
  51. $this->users[strtolower($user->getUsername())] = $user;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function loadUserByUsername($username)
  57. {
  58. if (!isset($this->users[strtolower($username)])) {
  59. throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
  60. }
  61. $user = $this->users[strtolower($username)];
  62. return new User($user->getUsername(), $user->getPassword(), $user->getRoles(), $user->isEnabled(), $user->isAccountNonExpired(),
  63. $user->isCredentialsNonExpired(), $user->isAccountNonLocked());
  64. }
  65. }