src/Security/ReservationVoter.php line 11

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