src/Security/Voter/BootCampVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. class BootCampVoter extends Voter
  7. {
  8.     public const NEW = 'new';
  9.     public const EDIT 'edit';
  10.     protected function supports(string $attribute$subject): bool
  11.     {
  12.         // replace with your own logic
  13.         // https://symfony.com/doc/current/security/voters.html
  14.         return in_array($attribute, [self::NEW, self::EDIT])
  15.             && $subject instanceof \App\Entity\BootCamp;
  16.     }
  17.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  18.     {
  19.         $user $token->getUser();
  20.         // if the user is anonymous, do not grant access
  21.         if (!$user instanceof UserInterface) {
  22.             return false;
  23.         }
  24.         return match ($attribute){
  25.             self::NEW => $this->canCreate($user),
  26.             self::EDIT => $this->canEdit($subject$user),
  27.             default => false
  28.         };
  29.     }
  30.     private function canCreate(
  31.         UserInterface $user
  32.     ): bool {
  33.         return in_array("ROLE_COACH"$user->getRoles());
  34.     }
  35.     private function canEdit(
  36.         mixed $subject,
  37.         UserInterface $user
  38.     ): bool {
  39.         return $this->canCreate($user) && $subject->getCoach()->getProfile()->getUser()->getUserIdentifier() === $user->getUserIdentifier();
  40.     }
  41. }