src/Security/Voter/TestimonyVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Testimony;
  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 TestimonyVoter extends Voter
  9. {
  10.     public const EDIT 'POST_EDIT';
  11.     public const VIEW 'POST_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::EDITself::VIEW])
  17.             && $subject instanceof \App\Entity\Testimony;
  18.     }
  19.     /**
  20.      * @param string $attribute
  21.      * @param Testimony $subject
  22.      * @param TokenInterface $token
  23.      * @return bool
  24.      */
  25.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  26.     {
  27.         /** @var User $user */
  28.         $user $token->getUser();
  29.         // if the user is anonymous, do not grant access
  30.         if (!$user instanceof UserInterface && !in_array("ROLE_COACH"$user->getRoles())) {
  31.             return false;
  32.         }
  33.         return match($attribute){
  34.             self::EDIT => $user->getProfile()->getCoach()->getUuid() == $subject->getCoach()->getUuid(),
  35.             default => false,
  36.         };
  37.     }
  38. }