src/Security/Voter/StoreVoter.php line 10

Open in your IDE?
  1. <?php 
  2. namespace App\Security\Voter;
  3. use App\Entity\Store;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class StoreVoter extends AbstractVoter
  9. {
  10.     const VIEW 'view';
  11.     const EDIT 'edit';
  12.     const DELETE 'delete';
  13.     private $security;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.     }
  18.     protected function supports($attribute$subject)
  19.     {
  20.         if (is_null($subject) || !$subject instanceof Store) {
  21.             return false;
  22.         }
  23.         $attribute $this->getActionFromAttribut($attribute);
  24.         // if the attribute isn't one we support, return false
  25.         if (!in_array($attribute, array(self::VIEWself::EDITself::DELETE))) {
  26.             return false;
  27.         }
  28.         return true;
  29.     }
  30.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  31.     {
  32.         $attribute $this->getActionFromAttribut($attribute);
  33.         
  34.         $user $token->getUser();
  35.         
  36.         if (!$user instanceof User) {
  37.             return false;
  38.         }
  39.         if ($this->security->isGranted('ROLE_ADMIN')) {
  40.             return true;
  41.         }
  42.         switch ($attribute) {
  43.             case self::VIEW:
  44.                 return $this->canView($subject$user);
  45.             case self::EDIT:
  46.                 return $this->canEdit($subject$user);
  47.             case self::DELETE:
  48.                 return $this->canDelete($subject$user);
  49.         }
  50.         throw new \LogicException('This code should not be reached!');
  51.     }
  52.     /**
  53.      * l'utilisateur peut voir la boutique si elle fait partie de ses boutiques
  54.      */
  55.     private function canView(Store $storeUser $user)
  56.     {
  57.         if( $user->getAdministrator()->getStores()->contains($store) ){
  58.             return true;
  59.         }
  60.         return false;
  61.     }
  62.     /**
  63.      * Même règle que pour voir
  64.      */
  65.     private function canEdit(Store $storeUser $user)
  66.     {
  67.         return $this->canView($store$user);
  68.     }
  69.     
  70.     /**
  71.      *  Même règle que pour voir
  72.      */
  73.     private function canDelete(Store $storeUser $user)
  74.     {
  75.         return $this->canView($store$user);
  76.     }
  77. }