src/Security/Voter/Api/RoomMessageVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Api;
  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. use function dd;
  7. class RoomMessageVoter extends Voter
  8. {
  9.     public const VIEW 'view';
  10.     public const NEW = 'new';
  11.     public const EDIT 'edit';
  12.     protected function supports(
  13.         string $attribute,
  14.         $subject
  15.     ): bool {
  16.         // replace with your own logic
  17.         // https://symfony.com/doc/current/security/voters.html
  18.         return in_array($attribute,
  19.                 [
  20.                     self::VIEW,
  21.                     self::NEW,
  22.                     self::EDIT
  23.                 ])
  24.             && $subject instanceof \App\Entity\RoomMessage;
  25.     }
  26.     protected function voteOnAttribute(
  27.         string $attribute,
  28.         $subject,
  29.         TokenInterface $token
  30.     ): bool {
  31.         $user $token->getUser();
  32.         // if the user is anonymous, do not grant access
  33.         if (!$user instanceof UserInterface) {
  34.             return false;
  35.         }
  36.         // ... (check conditions and return true to grant permission) ...
  37.         return match ($attribute) {
  38.             self::NEW => $this->canCreate($subject$user),
  39.             self::VIEW => $this->canView($subject$user),
  40.             default => false,
  41.         };
  42.     }
  43.     private function canCreate(
  44.         mixed $subject,
  45.         UserInterface $user
  46.     ): bool {
  47.         return
  48.         $subject->getAuthor()->getUserIdentifier() === $user->getUserIdentifier()
  49.             && $this->canView($subject$user);
  50.     }
  51.     private function canView(
  52.         mixed $subject,
  53.         UserInterface $user
  54.     ): bool {
  55.        return $subject->getRoom()->getCoach()->getUserIdentifier() === $user->getUserIdentifier()
  56.            || $subject->getRoom()->getClient()->getUserIdentifier() === $user->getUserIdentifier();
  57.     }
  58. }