<?php
namespace App\Security\Voter;
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\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class AdminUserVoter extends Voter
{
const CREATE = 'CREATE';
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, ['OWN_USER_EDIT']);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
//this causes error in Create User
// if (!$subject instanceof User) {
// throw new \LogicException('Subject is not an instance of User?');
// }
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'OWN_USER_EDIT':
return $user === $subject || $this->security->isGranted('ROLE_ADMIN_USER');
}
return false;
}
}