src/Security/Voter/ReservationVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  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\User\UserInterface;
  8. class ReservationVoter extends Voter
  9. {
  10.     public const VIEW 'view';
  11.     public const EDIT 'edit';
  12.     public const DELETE 'delete';
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         // replace with your own logic
  16.         // https://symfony.com/doc/current/security/voters.html
  17.         return in_array($attribute, [self::VIEWself::EDITself::DELETE])
  18.             && $subject instanceof Reservation;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         // if the user is anonymous, do not grant access
  24.         if (!$user instanceof UserInterface ) {
  25.             return false;
  26.         }
  27.         switch ($attribute) {
  28.             case self::VIEW:
  29.                 return $this->canView($subject$user);
  30.             case self::EDIT:
  31.                 return $this->canEdit($subject$user);
  32.             case self::DELETE:
  33.                 return $this->canDelete($subject$user);
  34.         }
  35.         return false;
  36.     }
  37.     private function canView(Reservation $reservationUser $user): bool
  38.     {
  39.         return $user->getClient() === $reservation->getClient() && $user->isReservationsEnable();
  40.     }
  41.     private function canDelete(Reservation $reservationUser $user): bool
  42.     {
  43.         $now = new \DateTime();
  44.         return $user->getClient() === $reservation->getClient() && $reservation->getStartDate() >= $now && $user->isReservationsEnable();
  45.     }
  46.     private function canEdit(Reservation $reservationUser $user): bool
  47.     {
  48.         $now = new \DateTime();
  49.         return $user->getClient() === $reservation->getClient() && $reservation->getStartDate() >= $now && $user->isReservationsEnable();
  50.     }
  51. }