DocumentUserProvider.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Symfony\Bundle\DoctrineMongoDBBundle\Security;
  3. use Symfony\Component\Security\User\AccountInterface;
  4. use Symfony\Component\Security\User\UserProviderInterface;
  5. use Symfony\Component\Security\Exception\UnsupportedAccountException;
  6. use Symfony\Component\Security\Exception\UsernameNotFoundException;
  7. class DocumentUserProvider implements UserProviderInterface
  8. {
  9. protected $class;
  10. protected $repository;
  11. protected $property;
  12. public function __construct($em, $class, $property = null)
  13. {
  14. $this->class = $class;
  15. if (false !== strpos($this->class, ':')) {
  16. $this->class = $em->getClassMetadata($class)->getName();
  17. }
  18. $this->repository = $em->getRepository($class);
  19. $this->property = $property;
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function loadUserByUsername($username)
  25. {
  26. if (null !== $this->property) {
  27. $user = $this->repository->findOneBy(array($this->property => $username));
  28. } else {
  29. if (!$this->repository instanceof UserProviderInterface) {
  30. throw new \InvalidArgumentException(sprintf('The Doctrine repository "%s" must implement UserProviderInterface.', get_class($this->repository)));
  31. }
  32. $user = $this->repository->loadUserByUsername($username);
  33. }
  34. if (null === $user) {
  35. throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
  36. }
  37. return $user;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function loadUserByAccount(AccountInterface $account)
  43. {
  44. if (!$account instanceof $this->class) {
  45. throw new UnsupportedAccountException(sprintf('Instances of "%s" are not supported.', get_class($account)));
  46. }
  47. return $this->loadUserByUsername((string) $account);
  48. }
  49. }