src/Security/Voter/AllowCommentsVoter.php line 11

  1. <?php
  2. namespace Cms\Security\Voter;
  3. use Cms\Entity\Post;
  4. use Symfony\Component\DependencyInjection\Attribute\Autowire;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class AllowCommentsVoter extends Voter
  9. {
  10.     public const VOTE 'comments_allowed';
  11.     public function __construct(
  12.         #[Autowire('%cms.allow_comments%')] private bool $allowComments
  13.     ) {}
  14.     protected function supports(string $attributemixed $subject): bool
  15.     {
  16.         return $subject instanceof Post && self::VOTE === $attribute;
  17.     }
  18.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  19.     {
  20.         /** @var Post $subject */
  21.         $user $token->getUser();
  22.         if (!$user instanceof UserInterface) {
  23.             return false;
  24.         }
  25.         if (null !== $subject->isCommentsAllowed()) {
  26.             return $subject->isCommentsAllowed();
  27.         }
  28.         if (null !== $subject->getCategory()->isCommentsAllowed()) {
  29.             return $subject->getCategory()->isCommentsAllowed();
  30.         }
  31.         return $this->allowComments;
  32.     }
  33. }