<?php
namespace AppBundle\Security\Voter;
use AppBundle\Entity\Booking;
use AppBundle\Entity\Customer;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class BookingVoter extends Voter
{
// these consts are the action that are voted on
public const EDIT = 'edit';
public const VIEW = 'view';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::VIEW])) {
return false;
}
// only vote on Booking objects inside this voter
if (!$subject instanceof Booking) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$customer = $token->getUser();
if (!$customer instanceof Customer) {
// the customer must be logged in; if not, deny access
return false;
}
// you know $subject is a Booking object, thanks to supports
/** @var Booking $booking */
$booking = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($booking, $customer, $token);
case self::EDIT:
return $this->canEdit($booking, $customer, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(Booking $booking, Customer $customer, TokenInterface $token)
{
// check if the customer is a admin
if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
return true;
}
return false;
}
private function canView(Booking $booking, Customer $customer, TokenInterface $token)
{
// if they can edit, they can view
if ($this->canEdit($booking, $customer, $token)) {
return true;
}
// check if the customer is associated with the booking
// and is therefore able to view it
if ($booking->getId() > 0) {
return $customer === $booking->getCustomer();
}
return false;
}
}