src/Security/Voter/DomainVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  7. use Symfony\Component\Security\Core\Security;
  8. class DomainVoter extends Voter
  9. {
  10.     private $security;
  11.     
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     
  17.     protected function supports($attribute$subject) : bool
  18.     {
  19.         // NEW actions don't yet have objects
  20.         if(in_array($attribute, ['NEW_DOMAIN'])) {
  21.             return true;
  22.         }
  23.             
  24.         return in_array($attribute, ['EDIT''DELETE'])
  25.             && $subject instanceof \App\Model\Domain;
  26.     }
  27.     
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token) : bool
  29.     {
  30.         $user $token->getUser();
  31.         // if the user is anonymous, do not grant access
  32.         if (!$user instanceof UserInterface) {
  33.             return false;
  34.         }
  35.         
  36.         switch ($attribute) {
  37.             case 'EDIT':
  38.             case 'DELETE':
  39.                 if($this->security->isGranted('ROLE_ADMIN')) {
  40.                     return true;
  41.                 }
  42.                 
  43.                 if($this->security->isGranted('ROLE_POSTMASTER')) {
  44.                     if(in_array($subject->getDomain(), $user->getDomains())) {
  45.                         return true;
  46.                     }
  47.                     
  48.                 }
  49.                 break;
  50.                                         
  51.             case 'NEW_DOMAIN':
  52.                 if($this->security->isGranted('ROLE_ADMIN')) {
  53.                     return true;
  54.                 }
  55.                 break;                    
  56.         }
  57.         
  58.         return false;
  59.     }
  60. }