src/WebserviceBundle/Security/WmsVoter.php line 19

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: mitchellherrijgers
  5.  * Date: 17-10-16
  6.  * Time: 13:43
  7.  */
  8. namespace WebserviceBundle\Security;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. use WmsBundle\Entity\User;
  12. /**
  13.  * Class WmsVoter
  14.  * @package WebserviceBundle\Security
  15.  */
  16. class WmsVoter extends Voter
  17. {
  18.     const WEB 'web';
  19.     const SCANNER 'scanner';
  20.     const BOTH 'web_or_scanner';
  21.     /**
  22.      * Determines if the attribute and subject are supported by this voter.
  23.      *
  24.      * @param string $attribute An attribute
  25.      * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
  26.      *
  27.      * @return bool True if the attribute and subject are supported, false otherwise
  28.      */
  29.     protected function supports($attribute$subject): bool
  30.     {
  31.         return $subject === null;
  32.     }
  33.     /**
  34.      * Perform a single access check operation on a given attribute, subject and token.
  35.      *
  36.      * @param string $attribute
  37.      * @param mixed $subject
  38.      * @param TokenInterface $token
  39.      *
  40.      * @return bool
  41.      */
  42.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  43.     {
  44.         switch ($attribute) {
  45.             case self::BOTH:
  46.                 return $this->hasRole($token'ROLE_SCANNER') || $this->hasRole($token'ROLE_WEB');
  47.             case self::WEB:
  48.                 return $this->hasRole($token'ROLE_WEB');
  49.             case self::SCANNER:
  50.                 return $this->hasRole($token'ROLE_SCANNER');
  51.             default:
  52.                 return false;
  53.         }
  54.     }
  55.     /**
  56.      * @param TokenInterface $token
  57.      * @param $role
  58.      * @return bool
  59.      */
  60.     private function hasRole(TokenInterface $token$role): bool
  61.     {
  62.         /** @var User $user */
  63.         $user $token->getUser();
  64.         if ($role === 'ROLE_WEB' && $user->getIsCustomer()) {
  65.             return true;
  66.         }
  67.         foreach ($token->getRoles() as $possibleRole) {
  68.             if ($possibleRole->getRole() === $role) {
  69.                 return true;
  70.             }
  71.         }
  72.         return false;
  73.     }
  74. }