src/Security/PromotionVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Promotion;
  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 PromotionVoter extends Voter
  9. {
  10.     const EDIT 'edit';
  11.     private Security $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     protected function supports(string $attribute$subject): bool
  17.     {
  18.         if (!$subject instanceof Promotion) {
  19.             return false;
  20.         }
  21.         return $attribute == self::EDIT;
  22.     }
  23.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  24.     {
  25.         $user $token->getUser();
  26.         // if the user is anonymous, do not grant access
  27.         if (!$user instanceof User) {
  28.             return false;
  29.         }
  30.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  31.             return true;
  32.         }
  33.         if ($attribute == self::EDIT) {
  34.             return $this->canEdit($subject$user);
  35.         }
  36.         throw new \LogicException('Unhandled attribute. Please check supports() method.');
  37.     }
  38.     private function canEdit(Promotion $subjectUser $user): bool
  39.     {
  40.         if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_PILOT')) {
  41.             return true;
  42.         }
  43.         if ($this->security->isGranted('ROLE_SPEAKER') || $this->security->isGranted('ROLE_SUPPORT')) {
  44.             return $subject->getStructure()->getId() === $user->getContact()->getStructure()->getId();
  45.         }
  46.         return false;
  47.     }
  48. }