src/Security/Voter/BootCampReservationVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\BootCampReservation;
  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\User\UserInterface;
  8. class BootCampReservationVoter extends Voter
  9. {
  10.     public const EDIT "edit";
  11.     public const VIEW "view";
  12.     protected function supports(string $attribute$subject): bool
  13.     {
  14.         // replace with your own logic
  15.         // https://symfony.com/doc/current/security/voters.html
  16.         return in_array($attribute, [self::VIEWself::EDIT])
  17.             && $subject instanceof \App\Entity\BootCampReservation;
  18.     }
  19.     /**
  20.      * @param string $attribute
  21.      * @param BootCampReservation $subject
  22.      * @param TokenInterface $token
  23.      * @return bool
  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 UserInterface) {
  30.             return false;
  31.         }
  32.         return match($attribute){
  33.             self::EDIT => $this->canEdit($user$subject),
  34.             "default" => false
  35.         };
  36.     }
  37.     private function canEdit(
  38.         UserInterface $user,
  39.         BootCampReservation $subject
  40.     ): bool {
  41.         return match(true){
  42.             in_array("ROLE_COACH"$user->getRoles()) => $user->getUserIdentifier() === $subject->getBootcamp()->getCoach()->getProfile()->getUser(),
  43.             default => $user->getUserIdentifier() === $subject->getClient()->getProfile()->getUser()->getUserIdentifier()
  44.         };
  45.     }
  46. }