<?php
namespace MedBrief\MSR\Security\Voter;
use MedBrief\MSR\Entity\HelpSection;
use MedBrief\MSR\Entity\User;
use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class HelpSectionVoter extends Voter
{
public const VIEW = 'VIEW';
public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
{
}
#[Override]
protected function supports($attribute, $subject): bool
{
return $attribute == self::VIEW
&& $subject instanceof HelpSection;
}
#[Override]
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;
}
/** @var HelpSection $helpSection */
$helpSection = $subject;
// ... (check conditions and return true to grant permission) ...
return match ($attribute) {
self::VIEW => $this->canView($helpSection),
default => false,
};
}
protected function canView(HelpSection $helpSection): bool
{
foreach ($helpSection->getArticles() as $article) {
if ($this->authorizationChecker->isGranted(HelpArticleVoter::VIEW, $article)) {
return true;
}
}
return false;
}
}