src/Security/Voter/Api/RoomVoter.php line 11

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