ChainUserProvider.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\Security\Core\User;
  11. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  12. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  13. /**
  14. * Chain User Provider.
  15. *
  16. * This provider calls several leaf providers in a chain until one is able to
  17. * handle the request.
  18. *
  19. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  20. */
  21. class ChainUserProvider implements UserProviderInterface
  22. {
  23. private $providers;
  24. public function __construct(array $providers)
  25. {
  26. $this->providers = $providers;
  27. }
  28. /**
  29. * @return array
  30. */
  31. public function getProviders()
  32. {
  33. return $this->providers;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function loadUserByUsername($username)
  39. {
  40. foreach ($this->providers as $provider) {
  41. try {
  42. return $provider->loadUserByUsername($username);
  43. } catch (UsernameNotFoundException $e) {
  44. // try next one
  45. }
  46. }
  47. $ex = new UsernameNotFoundException(sprintf('There is no user with name "%s".', $username));
  48. $ex->setUsername($username);
  49. throw $ex;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function refreshUser(UserInterface $user)
  55. {
  56. $supportedUserFound = false;
  57. foreach ($this->providers as $provider) {
  58. try {
  59. return $provider->refreshUser($user);
  60. } catch (UnsupportedUserException $e) {
  61. // try next one
  62. } catch (UsernameNotFoundException $e) {
  63. $supportedUserFound = true;
  64. // try next one
  65. }
  66. }
  67. if ($supportedUserFound) {
  68. $e = new UsernameNotFoundException(sprintf('There is no user with name "%s".', $user->getUsername()));
  69. $e->setUsername($user->getUsername());
  70. throw $e;
  71. } else {
  72. throw new UnsupportedUserException(sprintf('The account "%s" is not supported.', \get_class($user)));
  73. }
  74. }
  75. /**
  76. * {@inheritdoc}
  77. */
  78. public function supportsClass($class)
  79. {
  80. foreach ($this->providers as $provider) {
  81. if ($provider->supportsClass($class)) {
  82. return true;
  83. }
  84. }
  85. return false;
  86. }
  87. }