<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\Record;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
class RecordVoter extends Voter
{
public function __construct(private readonly Security $security)
{
}
protected function supports($attribute, $subject): bool
{
// only vote on `Record` objects
if (!$subject instanceof Record) {
return false;
}
// if the attribute isn't one we support, return false
return $attribute == 'view';
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/**@var Record $record */
$record = $subject;
$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 view THEIR records
'view' => $user === $record->getUser(),
default => false,
};
}
}