src/Security/CustomerVoter.php line 19

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 App\Entity\Customer;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  13. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  14. class CustomerVoter extends Voter
  15. {
  16.     const VIEW 'customer_show';
  17.     const EDIT 'customer_edit';
  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 Customer) {
  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.         $customer $subject;
  40.         switch ($attribute) {
  41.             case self::VIEW:
  42.                 return $this->canView($customer$user);
  43.             case self::EDIT:
  44.                 return $this->canEdit($customer$user);
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     private function canView(Customer $customerAdmin $admin)
  49.     {
  50.         if($this->canEdit($customer$admin)) {
  51.             return true;
  52.         }
  53.         return false;
  54.     }
  55.     private function canEditCustomer $customerAdmin $admin)
  56.     {
  57.         $admins $customer->getAdmins();
  58.         foreach ($admins as $adminAct) {
  59.             if ($admin === $adminAct) {
  60.                 return true;
  61.             }
  62.         }
  63.         return false;
  64.     }
  65. }