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 string $prefix;
  20. public function __construct(string $prefix = 'ROLE_')
  21. {
  22. $this->prefix = $prefix;
  23. }
  24. public function vote(TokenInterface $token, mixed $subject, array $attributes): int
  25. {
  26. $result = VoterInterface::ACCESS_ABSTAIN;
  27. $roles = $this->extractRoles($token);
  28. foreach ($attributes as $attribute) {
  29. if (!\is_string($attribute) || !str_starts_with($attribute, $this->prefix)) {
  30. continue;
  31. }
  32. $result = VoterInterface::ACCESS_DENIED;
  33. foreach ($roles as $role) {
  34. if ($attribute === $role) {
  35. return VoterInterface::ACCESS_GRANTED;
  36. }
  37. }
  38. }
  39. return $result;
  40. }
  41. public function supportsAttribute(string $attribute): bool
  42. {
  43. return str_starts_with($attribute, $this->prefix);
  44. }
  45. public function supportsType(string $subjectType): bool
  46. {
  47. return true;
  48. }
  49. /**
  50. * @return array
  51. */
  52. protected function extractRoles(TokenInterface $token)
  53. {
  54. return $token->getRoleNames();
  55. }
  56. }