src/Security/HotelVoter.php line 12

Open in your IDE?
  1. <?php
  2. // src/Security/HotelVoter.php
  3. namespace App\Security;
  4. use App\Entity\Hotel;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class HotelVoter extends Voter
  10. {
  11.     const VIEW 'view';
  12.     const EDIT 'edit';
  13.     
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }    
  19.     protected function supports(string $attribute$subject): bool
  20.     {
  21.         // if the attribute isn't one we support, return false
  22.         if (!in_array($attribute, [self::VIEWself::EDIT])) {
  23.             return false;
  24.         }
  25.         // only vote on `Hotel` objects
  26.         if (!$subject instanceof Hotel) {
  27.             return false;
  28.         }
  29.         return true;
  30.     }
  31.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  32.     {
  33.         $user $token->getUser();
  34.         if (!$user instanceof User) {
  35.             // the user must be logged in; if not, deny access
  36.             return false;
  37.         }
  38.         // you know $subject is a Hotel object, thanks to `supports()`
  39.         /** @var Hotel $hotel */
  40.         $hotel $subject;
  41.         switch ($attribute) {
  42.             case self::VIEW:
  43.                 return $this->canView($hotel$user);
  44.             case self::EDIT:
  45.                 return $this->canEdit();
  46.         }
  47.         throw new \LogicException('This code should not be reached!');
  48.     }
  49.     private function canView(Hotel $hotelUser $user): bool
  50.     {
  51.         $hotel_users $hotel->getHotelUsers();
  52.         foreach($hotel_users as $hu){
  53.             if($hu->getUser() == $user){
  54.                 return true;
  55.             }
  56.         }
  57.         // the Hotel object could have, for example, a method `isPrivate()`
  58.         return false;
  59.     }
  60.     private function canEdit(): bool
  61.     {
  62.         if ($this->security->isGranted('ROLE_ADMIN')) {
  63.             return true;
  64.         }
  65.         
  66.         return false;
  67.     }
  68. }