<?php
declare(strict_types=1);
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;
class UserVoter extends Voter
{
private const ATTRIBUTES = ['READ', 'UPDATE', 'DELETE'];
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param mixed $subject
* @return bool
*/
protected function supports(string $attribute, $subject)
{
return ($subject instanceof User);
}
/**
* @param User $subject
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
if (!in_array($attribute, self::ATTRIBUTES, true)) {
return false;
}
/** @var User $currentUser */
$currentUser = $token->getUser();
if (!$currentUser instanceof User) {
return false;
}
return (
$attribute === 'READ'
|| $subject->getId() === $currentUser->getId()
|| $this->security->isGranted('ROLE_ADMIN')
);
}
}