vendor/league/tactician-bundle/src/Security/Voter/HandleCommandVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace League\Tactician\Bundle\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. /**
  7.  * Voter for security checks on handling commands.
  8.  *
  9.  * @author Ron Rademaker
  10.  */
  11. class HandleCommandVoter extends Voter
  12. {
  13.     /**
  14.      * The decision manager.
  15.      *
  16.      * @var AccessDecisionManagerInterface
  17.      */
  18.     private $decisionManager;
  19.     /**
  20.      * Command - Require role mapping
  21.      *
  22.      * @var array
  23.      */
  24.     private $commandRoleMapping = [];
  25.     /**
  26.      * Create a new HandleCommandVoter.
  27.      *
  28.      * @param AccessDecisionManagerInterface $decisionManager
  29.      * @param array                          $commandRoleMapping
  30.      */
  31.     public function __construct(AccessDecisionManagerInterface $decisionManager, array $commandRoleMapping = [])
  32.     {
  33.         $this->decisionManager $decisionManager;
  34.         $this->commandRoleMapping $commandRoleMapping;
  35.     }
  36.     /**
  37.      * The voter supports checking handle commands
  38.      *
  39.      * @param string $attribute
  40.      * @param object $subject
  41.      *
  42.      * @return bool
  43.      */
  44.     protected function supports($attribute$subject): bool
  45.     {
  46.         return $attribute === 'handle' && is_object($subject);
  47.     }
  48.     /**
  49.      * Checks if the currently logged on user may handle $subject.
  50.      *
  51.      * @param string         $attribute
  52.      * @param mixed          $subject
  53.      * @param TokenInterface $token
  54.      *
  55.      * @return bool
  56.      */
  57.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  58.     {
  59.         $allowedRoles $this->getAllowedRoles(get_class($subject));
  60.         if (count($allowedRoles) > 0) {
  61.             return $this->decisionManager->decide($token$allowedRoles);
  62.         }
  63.         // default conclusion is access denied
  64.         return false;
  65.     }
  66.     /**
  67.      * Gets the roles allowed to handle a command of $type
  68.      *
  69.      * @param string $type
  70.      *
  71.      * @return array
  72.      */
  73.     private function getAllowedRoles(string $type)
  74.     {
  75.         if (array_key_exists($type$this->commandRoleMapping)) {
  76.             return $this->commandRoleMapping[$type];
  77.         }
  78.         return [];
  79.     }
  80. }