<?php
namespace MedBrief\MSR\Security\Voter;
use InvalidArgumentException;
use MedBrief\MSR\Entity\ExpertReportRequestDetail;
use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class ExpertReportRequestDetailVoter implements VoterInterface
{
public const UPDATE = 'UPDATE';
public const DELETE = 'DELETE';
public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
{
}
public function supportsAttribute($attribute): bool
{
return in_array($attribute, [
self::UPDATE,
self::DELETE,
]);
}
public function supportsClass($class): bool
{
$supportedClass = ExpertReportRequestDetail::class;
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
#[Override]
public function vote(TokenInterface $token, $entity, array $attributes)
{
if (!$this->supportsClass($entity && !is_array($entity) ? $entity::class : '')) {
return VoterInterface::ACCESS_ABSTAIN;
}
if (1 !== count($attributes)) {
throw new InvalidArgumentException(
'Only one attribute is allowed for Medbrief Voters.'
);
}
$attribute = $attributes[0];
if (!$this->supportsAttribute($attribute)) {
return VoterInterface::ACCESS_ABSTAIN;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return VoterInterface::ACCESS_DENIED;
}
// Admin users can do everything
if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
return VoterInterface::ACCESS_GRANTED;
}
// Follow other *RequestDetailVoter patterns: only the creator (or ROLE_ADMIN above) may UPDATE/DELETE.
if (in_array($attribute, [self::UPDATE, self::DELETE], true)
&& $entity->getCreator()
&& $entity->getCreator()->getId() === $user->getId()
) {
return VoterInterface::ACCESS_GRANTED;
}
return VoterInterface::ACCESS_DENIED;
}
}