vendor/symfony/security/Core/Authorization/Voter/RoleVoter.php line 22

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. use Symfony\Component\Security\Core\Role\Role;
  13. /**
  14.  * RoleVoter votes if any attribute starts with a given prefix.
  15.  *
  16.  * @author Fabien Potencier <fabien@symfony.com>
  17.  */
  18. class RoleVoter implements VoterInterface
  19. {
  20.     private $prefix;
  21.     public function __construct(string $prefix 'ROLE_')
  22.     {
  23.         $this->prefix $prefix;
  24.     }
  25.     /**
  26.      * {@inheritdoc}
  27.      */
  28.     public function vote(TokenInterface $token$subject, array $attributes)
  29.     {
  30.         $result VoterInterface::ACCESS_ABSTAIN;
  31.         $roles $this->extractRoles($token);
  32.         foreach ($attributes as $attribute) {
  33.             if ($attribute instanceof Role) {
  34.                 $attribute $attribute->getRole();
  35.             }
  36.             if (!\is_string($attribute) || !str_starts_with($attribute$this->prefix)) {
  37.                 continue;
  38.             }
  39.             $result VoterInterface::ACCESS_DENIED;
  40.             foreach ($roles as $role) {
  41.                 if ($attribute === $role) {
  42.                     return VoterInterface::ACCESS_GRANTED;
  43.                 }
  44.             }
  45.         }
  46.         return $result;
  47.     }
  48.     protected function extractRoles(TokenInterface $token)
  49.     {
  50.         if (method_exists($token'getRoleNames')) {
  51.             return $token->getRoleNames();
  52.         }
  53.         @trigger_error(sprintf('Not implementing the "%s::getRoleNames()" method in "%s" is deprecated since Symfony 4.3.'TokenInterface::class, \get_class($token)), \E_USER_DEPRECATED);
  54.         return array_map(function (Role $role) { return $role->getRole(); }, $token->getRoles(false));
  55.     }
  56. }