/src/Symfony/Component/Security/Core/Authorization/Voter/RoleVoter.php

http://github.com/symfony/symfony · PHP · 62 lines · 35 code · 11 blank · 16 comment · 4 complexity · 491d6312ce06d275c413cb61bf33c4de MD5 · raw file

  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\Authorization\Voter;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. /**
  13. * RoleVoter votes if any attribute starts with a given prefix.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class RoleVoter implements VoterInterface
  18. {
  19. private $prefix;
  20. public function __construct(string $prefix = 'ROLE_')
  21. {
  22. $this->prefix = $prefix;
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function vote(TokenInterface $token, $subject, array $attributes)
  28. {
  29. $result = VoterInterface::ACCESS_ABSTAIN;
  30. $roles = $this->extractRoles($token);
  31. foreach ($attributes as $attribute) {
  32. if (!\is_string($attribute) || 0 !== strpos($attribute, $this->prefix)) {
  33. continue;
  34. }
  35. if ('ROLE_PREVIOUS_ADMIN' === $attribute) {
  36. trigger_deprecation('symfony/security-core', '5.1', 'The ROLE_PREVIOUS_ADMIN role is deprecated and will be removed in version 6.0, use the IS_IMPERSONATOR attribute instead.');
  37. }
  38. $result = VoterInterface::ACCESS_DENIED;
  39. foreach ($roles as $role) {
  40. if ($attribute === $role) {
  41. return VoterInterface::ACCESS_GRANTED;
  42. }
  43. }
  44. }
  45. return $result;
  46. }
  47. protected function extractRoles(TokenInterface $token)
  48. {
  49. return $token->getRoleNames();
  50. }
  51. }