src/AppBundle/Security/Voter/BookingVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security\Voter;
  3. use AppBundle\Entity\Booking;
  4. use AppBundle\Entity\Customer;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class BookingVoter extends Voter
  9. {
  10.     // these consts are the action that are voted on
  11.     public const EDIT 'edit';
  12.     public const VIEW 'view';
  13.     private $decisionManager;
  14.     public function __construct(AccessDecisionManagerInterface $decisionManager)
  15.     {
  16.         $this->decisionManager $decisionManager;
  17.     }
  18.     protected function supports($attribute$subject)
  19.     {
  20.         // if the attribute isn't one we support, return false
  21.         if (!in_array($attribute, [self::EDITself::VIEW])) {
  22.             return false;
  23.         }
  24.         // only vote on Booking objects inside this voter
  25.         if (!$subject instanceof Booking) {
  26.             return false;
  27.         }
  28.         return true;
  29.     }
  30.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  31.     {
  32.         $customer $token->getUser();
  33.         if (!$customer instanceof Customer) {
  34.             // the customer must be logged in; if not, deny access
  35.             return false;
  36.         }
  37.         // you know $subject is a Booking object, thanks to supports
  38.         /** @var Booking $booking */
  39.         $booking $subject;
  40.         switch ($attribute) {
  41.             case self::VIEW:
  42.                 return $this->canView($booking$customer$token);
  43.             case self::EDIT:
  44.                 return $this->canEdit($booking$customer$token);
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     private function canEdit(Booking $bookingCustomer $customerTokenInterface $token)
  49.     {
  50.         // check if the customer is a admin
  51.         if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
  52.             return true;
  53.         }
  54.         return false;
  55.     }
  56.     private function canView(Booking $bookingCustomer $customerTokenInterface $token)
  57.     {
  58.         // if they can edit, they can view
  59.         if ($this->canEdit($booking$customer$token)) {
  60.             return true;
  61.         }
  62.         // check if the customer is associated with the booking
  63.         // and is therefore able to view it
  64.         if ($booking->getId() > 0) {
  65.             return $customer === $booking->getCustomer();
  66.         }
  67.         return false;
  68.     }
  69. }