src/Security/AdminVoter.php line 18

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: sebastien.nexon
  5.  * Date: 26/01/2018
  6.  * Time: 11:30
  7.  */
  8. namespace App\Security;
  9. use App\Entity\Admin;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  12. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  13. class AdminVoter extends Voter
  14. {
  15.     const VIEW 'admin_show';
  16.     const EDIT 'admin_edit';
  17.     const ADMIN_VIEW 'ADMIN_VIEW';
  18.     private $decisionManager;
  19.     public function __construct(AccessDecisionManagerInterface $decisionManager)
  20.     {
  21.         $this->decisionManager $decisionManager;
  22.     }
  23.     protected function supports($attribute$subject)
  24.     {
  25.         if(!in_array($attribute, array(self::VIEW,self::EDIT))) {
  26.             return false;
  27.         }
  28.         if(!$subject instanceof Admin) {
  29.             return false;
  30.         }
  31.         return true;
  32.     }
  33.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  34.     {
  35.         $user $token->getUser();
  36.         if ($this->decisionManager->decide($token, array('ROLE_SUPER_ADMIN'))) {
  37.             return true;
  38.         }
  39.         /** @var Admin $admin */
  40.         $admin $subject;
  41.         if ($user->hasRole(Admin::ROLE_CUSTOMER)) {
  42.             return false;
  43.         }
  44.         switch ($attribute) {
  45.             case self::VIEW:
  46.                 return $this->canView($user$admin);
  47.             case self::EDIT:
  48.                 return $this->canEdit($user$admin);
  49.         }
  50.         throw new \LogicException('This code should not be reached!');
  51.     }
  52.     private function canView(Admin $userAdmin $admin)
  53.     {
  54.         if($this->canEdit($user$admin)) {
  55.             return true;
  56.         }
  57.         return false;
  58.     }
  59.     private function canEditAdmin $userAdmin $target)
  60.     {
  61.         if ($target === $user || $target->getAuthorizedAdmins()->contains($user)) {
  62.             return true;
  63.         }
  64.         return false;
  65.     }
  66. }