<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Helper\PermissionsHandlerInterface;
use App\Repository\UserRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class AppVoter extends Voter
{
/**
* @var UserRepository
*/
protected UserRepository $userRepository;
/**
* @var PermissionsHandlerInterface
*/
protected PermissionsHandlerInterface $permissionsHandler;
/**
* @var User|null
*/
protected $loggedUser;
/**
* @var array
*/
protected $permissions;
public function __construct(
UserRepository $userRepository,
PermissionsHandlerInterface $permissionsHandler,
Security $security
) {
$this->userRepository = $userRepository;
$this->permissionsHandler = $permissionsHandler;
$this->permissions = array_keys($permissionsHandler->getPermissions());
$this->loggedUser = $security->getUser();
}
protected function supports($attribute, $subject)
{
if (!empty($this->loggedUser) && in_array('ROLE_ADMIN', $this->loggedUser->getRoles())) {
return true;
}
return in_array(strtoupper($attribute), $this->permissions);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if (!empty($this->loggedUser) && in_array('ROLE_ADMIN', $this->loggedUser->getRoles())) {
return true;
}
$attribute = strtoupper($attribute);
if (empty($this->loggedUser) || !in_array($attribute, $this->permissions)) {
return false;
}
$user = $this->userRepository->findOneBy(['email' => $this->loggedUser->getUsername()]);
return $user->getRole()->hasPermission($attribute);
}
}