src/Security/Voter/HelpSectionVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Security\Voter;
  3. use MedBrief\MSR\Entity\HelpSection;
  4. use MedBrief\MSR\Entity\User;
  5. use Override;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class HelpSectionVoter extends Voter
  11. {
  12. public const VIEW = 'VIEW';
  13. public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
  14. {
  15. }
  16. #[Override]
  17. protected function supports($attribute, $subject): bool
  18. {
  19. return $attribute == self::VIEW
  20. && $subject instanceof HelpSection;
  21. }
  22. #[Override]
  23. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  24. {
  25. $user = $token->getUser();
  26. // if the user is anonymous, do not grant access
  27. if (!$user instanceof UserInterface) {
  28. return false;
  29. }
  30. /** @var HelpSection $helpSection */
  31. $helpSection = $subject;
  32. // ... (check conditions and return true to grant permission) ...
  33. return match ($attribute) {
  34. self::VIEW => $this->canView($helpSection),
  35. default => false,
  36. };
  37. }
  38. protected function canView(HelpSection $helpSection): bool
  39. {
  40. foreach ($helpSection->getArticles() as $article) {
  41. if ($this->authorizationChecker->isGranted(HelpArticleVoter::VIEW, $article)) {
  42. return true;
  43. }
  44. }
  45. return false;
  46. }
  47. }