src/Security/ConsultantVoter.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\Consultant;
  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 ConsultantVoter extends Voter
  15. {
  16.     const VIEW 'consultant_show';
  17.     const EDIT 'consultant_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 Consultant) {
  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.         $consultant $subject;
  40.         switch ($attribute) {
  41.             case self::VIEW:
  42.                 return $this->canView($consultant$user);
  43.             case self::EDIT:
  44.                 return $this->canEdit($consultant$user);
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     private function canView(Consultant $consultantAdmin $admin)
  49.     {
  50.         if($this->canEdit($consultant$admin)) {
  51.             return true;
  52.         }
  53.         return false;
  54.     }
  55.     private function canEdit(Consultant $consultantAdmin $admin)
  56.     {
  57.         if(empty($consultant->getJobs())) {
  58.             return false;
  59.         }
  60.         else {
  61.             $admins = array();
  62.             foreach ($consultant->getJobs() as $job)
  63.             {
  64.                 $admins[] = $job->getContract()->getCustomer()->getAdmins();
  65.             }
  66.             foreach ($admins as $adminAct) {
  67.                 if($admin === $adminAct) {
  68.                     return true;
  69.                 }
  70.             }
  71.         }
  72.         return false;
  73.     }
  74. }