UserValueResolver.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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\Http\Controller;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
  13. use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
  14. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  15. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  16. use Symfony\Component\Security\Core\User\UserInterface;
  17. use Symfony\Component\Security\Http\Attribute\CurrentUser;
  18. /**
  19. * Supports the argument type of {@see UserInterface}.
  20. *
  21. * @author Iltar van der Berg <kjarli@gmail.com>
  22. */
  23. final class UserValueResolver implements ArgumentValueResolverInterface
  24. {
  25. private $tokenStorage;
  26. public function __construct(TokenStorageInterface $tokenStorage)
  27. {
  28. $this->tokenStorage = $tokenStorage;
  29. }
  30. public function supports(Request $request, ArgumentMetadata $argument): bool
  31. {
  32. // with the attribute, the type can be any UserInterface implementation
  33. // otherwise, the type must be UserInterface
  34. if (UserInterface::class !== $argument->getType() && !$argument->getAttribute() instanceof CurrentUser) {
  35. return false;
  36. }
  37. $token = $this->tokenStorage->getToken();
  38. if (!$token instanceof TokenInterface) {
  39. return false;
  40. }
  41. $user = $token->getUser();
  42. // in case it's not an object we cannot do anything with it; E.g. "anon."
  43. return $user instanceof UserInterface;
  44. }
  45. public function resolve(Request $request, ArgumentMetadata $argument): iterable
  46. {
  47. yield $this->tokenStorage->getToken()->getUser();
  48. }
  49. }