src/Security/PlanningVoter.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\Planning;
  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 PlanningVoter extends Voter
  15. {
  16.     const VIEW 'planning_index';
  17.     private $decisionManager;
  18.     public function __construct(AccessDecisionManagerInterface $decisionManager)
  19.     {
  20.         $this->decisionManager $decisionManager;
  21.     }
  22.     protected function supports($attribute$subject)
  23.     {
  24.         if(!in_array($attribute, array(self::VIEW))) {
  25.             return false;
  26.         }
  27.         if(!$subject instanceof Planning) {
  28.             return false;
  29.         }
  30.         return true;
  31.     }
  32.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  33.     {
  34.         $user $token->getUser();
  35.         if ($this->decisionManager->decide($token, array('ROLE_SUPER_ADMIN'))) {
  36.             return true;
  37.         }
  38.         $planning $subject;
  39.         switch ($attribute) {
  40.             case self::VIEW:
  41.                 return $this->canView($planning$user);
  42.         }
  43.         throw new \LogicException('This code should not be reached!');
  44.     }
  45.     private function canViewPlanning $planningAdmin $admin)
  46.     {
  47.         $customer $planning->getJob()->getContract()->getCustomer();
  48.         $authorizedUsers array_merge($customer->getAdmins()->toArray(), $customer->getViewers()->toArray());
  49.         foreach ($authorizedUsers as $authorizedUser) {
  50.             if($admin === $authorizedUser) {
  51.                 return true;
  52.             }
  53.         }
  54.         return false;
  55.     }
  56. }