<?php
namespace App\Security\Voter;
use App\Entity\AuthUser;
use App\Entity\UserAction;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class ApplicationVoter extends Voter
{
/** @var Security */
private Security $security;
/** @var EntityManagerInterface */
private EntityManagerInterface $em;
public function __construct(Security $security, EntityManagerInterface $em)
{
$this->security = $security;
$this->em = $em;
}
protected function supports(string $attribute, $subject): bool
{
return in_array(
$attribute,
[
'ADD',
'EDIT',
'DELETE',
'READ_COLLECTION',
'READ_ITEM',
'VALIDATE',
'OUTER_COMMUNICATION'
]);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if (!$attribute || !$subject) {
return false;
}
/** @var AuthUser $user */
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($this->security->isGranted("ROLE_SUPER_ADMIN")) {
return true;
}
$actions = $this->em->getRepository(UserAction::class)->findOneBy([
'authUser' => $user,
'objectName' => $subject
]);
if ($actions) {
$functionName = sprintf('get%s', $this->snakeToCamel($attribute));
return $actions->{$functionName}();
}
return VoterInterface::ACCESS_DENIED;
}
private function snakeToCamel($str)
{
return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($str))));
}
}