<?php
namespace AppBundle\Security\Voter;
use AppBundle\Entity\Customer;
use AppBundle\Entity\Holiday;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class HolidayVoter extends Voter
{
// these consts are the action that are voted on
public const EDIT = 'edit';
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])) {
return false;
}
// only vote on Holiday objects inside this voter
if (!$subject instanceof Holiday) {
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 Holiday object, thanks to supports
/** @var Holiday $holiday */
$holiday = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($holiday, $customer, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(Holiday $holiday, Customer $customer, TokenInterface $token)
{
// check if the customer is a admin
if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
return true;
}
return false;
}
}