src/Security/Voter/LessonVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Lesson;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class LessonVoter extends Voter
  8. {
  9.     public const EDIT 'edit';
  10.     public const VIEW 'view';
  11.     protected function supports(string $attribute$subject): bool
  12.     {
  13.         // replace with your own logic
  14.         // https://symfony.com/doc/current/security/voters.html
  15.         return in_array($attribute, [self::EDIT,self::VIEW])
  16.             && $subject instanceof Lesson;
  17.     }
  18.     /**
  19.      * @param string $attribute
  20.      * @param Lesson $subject
  21.      * @param TokenInterface $token
  22.      * @return bool
  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 UserInterface) {
  29.             return false;
  30.         }
  31.         // ... (check conditions and return true to grant permission) ...
  32.         return match ($attribute) {
  33.             self::EDIT => $this->canEdit($user$subject),
  34.             self::VIEW => $this->canView($user$subject),
  35.             default => false,
  36.         };
  37.     }
  38.     private function canEdit(
  39.         UserInterface $user,
  40.         Lesson $subject
  41.     ) {
  42.         return $user->getUserIdentifier() === $subject->getCoach()->getProfile()->getUser()->getUserIdentifier()
  43.             || $user->getUserIdentifier() === $subject->getAuthor()->getUserIdentifier();
  44.     }
  45.     private function canView(
  46.         UserInterface $user,
  47.         Lesson $subject
  48.     ) {
  49.         $otherUser array_filter($subject->getAdditionalClient(), function ($client) use ($user) {
  50.             return $user->getUserIdentifier() === $client->getProfile()->getUser()->getUserIdentifier();
  51.         });
  52.         return $this->canEdit($user$subject) || !empty($otherUser);
  53.     }
  54. }