src/Security/ContactVoter.php line 12

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