src/Security/Voter/IsOwnerVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\AppTrainingUser;
  4. use App\Entity\Establishment;
  5. use App\Entity\Program;
  6. use App\Entity\Session;
  7. use App\Entity\User;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. use Symfony\Component\Security\Core\Security;
  11. use Symfony\Component\Security\Core\User\UserInterface;
  12. class IsOwnerVoter extends Voter
  13. {
  14.     public function __construct(private readonly Security $security)
  15.     {
  16.     }
  17.     protected function supports(string $attribute$subject): bool
  18.     {
  19.         return $attribute == 'IS_DOCTOR_AND_OWNER';
  20.     }
  21.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         // if the user is anonymous, do not grant access
  25.         if (!$user instanceof UserInterface) {
  26.             return false;
  27.         }
  28.         // si la personne n'est pas docteur, accès interdit
  29.         if (!$this->security->isGranted('ROLE_DOCTOR')) {
  30.             return false;
  31.         }
  32.         if ($subject instanceof Session || $subject instanceof Program) {
  33.             if ($user->getEstablishment() instanceof Establishment) {
  34.                 if ($subject->getEstablishment() === $user->getEstablishment()) {
  35.                     return true;
  36.                 }
  37.             }
  38.         }
  39.         if ($subject instanceof AppTrainingUser) {
  40.             if ($subject->getUser() instanceof User &&
  41.                 $subject->getUser()->getEstablishment() instanceof Establishment &&
  42.                 $subject->getUser()->getEstablishment() === $user->getEstablishment()) {
  43.                 return true;
  44.             }
  45.         }
  46.         return false;
  47.     }
  48. }