<?php
namespace App\Security\Voter;
use App\Component\UserRole\Manager\UserRoleManager;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class UserRoleVoter extends Voter
{
private UserRoleManager $userRoleManager;
/**
* UserRoleVoter constructor.
*/
public function __construct(UserRoleManager $userRoleManager)
{
$this->userRoleManager = $userRoleManager;
}
protected function supports($attribute, $subject): bool
{
if (0 === mb_strpos($attribute, 'ROLE_')) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
if (!$token->hasAttribute('user_role_entries')) {
return false;
}
$roles = $user->getUserRoles();
if (!\in_array($attribute, array_keys($this->userRoleManager->getMasks()), true)) {
return false;
}
$entries = $token->getAttribute('user_role_entries');
if (!\array_key_exists($subject, $entries) || $entries[$subject] & $attribute) {
return true;
}
return false;
}
}