<?php
declare(strict_types=1);
namespace App\Security;
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\Contracts\Service\Attribute\Required;
class UserVoter extends Voter{
const EDIT = 'edit';
#[Required]
public Security $security;
protected function supports(string $attribute, mixed $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT])) {
return false;
}
// only vote on `User` objects
if (!$subject instanceof User) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$userConnected = $token->getUser();
if (!$userConnected instanceof User) {
return false;
}
/** @var User $user */
$user = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($user, $userConnected);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(User $user, User $userConnected): bool
{
if($this->security->isGranted('ROLE_ADMIN')){
return true;
}
return false;
}
}