vendor/symfony/security-core/Authorization/Voter/RoleVoter.php line 21

Open in your IDE?
  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 CacheableVoterInterface
  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) || !str_starts_with($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. public function supportsAttribute(string $attribute): bool
  48. {
  49. return str_starts_with($attribute, $this->prefix);
  50. }
  51. public function supportsType(string $subjectType): bool
  52. {
  53. return true;
  54. }
  55. protected function extractRoles(TokenInterface $token)
  56. {
  57. return $token->getRoleNames();
  58. }
  59. }