<?php
namespace AppBundle\Security;
use AppBundle\Entity\EntityActionsInterface;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Class EntityActionsVoter.
*/
class EntityActionsVoter extends Voter
{
/**
* @var AuthorizationCheckerInterface
*/
private $authorizationChecker;
/**
* EntityActionVoter constructor.
*
* @param AuthorizationCheckerInterface $authorizationChecker
*/
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject)
{
if (!in_array($attribute, $this->getSupportedAttributes())) {
return false;
}
return $subject instanceof EntityActionsInterface;
}
/**
* {@inheritdoc}
* @param EntityActionsInterface $subject
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
foreach ($subject->getDeleteActionRoles() as $role) {
if (!$this->authorizationChecker->isGranted($role, $subject)) {
return false;
}
}
return true;
}
/**
* @return array
*/
private function getSupportedAttributes(): array
{
return [
EntityActionsInterface::DELETE_ACTION,
];
}
}