src/Security/Voter/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Room;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class UserVoter extends Voter
  8. {
  9.   protected function supports($attribute$subject): bool
  10.   {
  11.     $supportsAttribute in_array($attribute, ['IS_OWNER']);
  12.     $supportsSubject $subject instanceof User;
  13.     return $supportsAttribute && $supportsSubject;
  14.   }
  15.   /**
  16.    * @param string $attribute
  17.    * @param User $subject
  18.    * @param TokenInterface $token
  19.    * @return bool
  20.    */
  21.   protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  22.   {
  23.     $user $token->getUser();
  24.     if (!$user instanceof User) {
  25.       return false;
  26.     }
  27.     switch ($attribute) {
  28.       case 'IS_OWNER':
  29.         if ($user === $subject) {
  30.           return true;
  31.         }
  32.       case 'ROOM_ADMIN':
  33.         /** @var Room $subject */
  34.         if ($subject->getAdmins()->contains($user)) {
  35.           return true;
  36.         }
  37.     }
  38.     return false;
  39.   }
  40. }