<?php
declare(strict_types=1);
namespace App\Security\Voter;
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 UserVoter extends Voter
{
public function __construct(private readonly Security $security)
{
}
protected function supports($attribute, $subject): bool
{
// only vote on `User` objects
if (!$subject instanceof UserInterface) {
return false;
}
// if the attribute isn't one we support, return false
return $attribute == 'edit';
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ROLE_CHIEF can do anything! The power!
if ($this->security->isGranted('ROLE_CHIEF')) {
return true;
}
return match ($attribute) {
// Users may edit themself
'edit' => $user === $subject,
default => false,
};
}
}