src/Security/BeneficiaryVoter.php line 13

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