src/Security/Voter/ForumVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\ForumReponse;
  4. use App\Entity\Sujetforum;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ForumVoter extends Voter
  9. {
  10.     public const REPONSE_EDIT 'FORUM_REPONSE_EDIT';
  11.     public const REPONSE_DELETE 'FORUM_REPONSE_DELETE';
  12.     public const SUJET_EDIT 'FORUM_SUJET_EDIT';
  13.     public const SUJET_DELETE 'FORUM_SUJET_DELETE';
  14.     protected function supports(string $attributemixed $subject): bool
  15.     {
  16.         if ($subject instanceof ForumReponse) {
  17.             return \in_array($attribute, [self::REPONSE_EDITself::REPONSE_DELETE], true);
  18.         }
  19.         if ($subject instanceof Sujetforum) {
  20.             return \in_array($attribute, [self::SUJET_EDITself::SUJET_DELETE], true);
  21.         }
  22.         return false;
  23.     }
  24.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  25.     {
  26.         $user $token->getUser();
  27.         if (!$user instanceof User) {
  28.             return false;
  29.         }
  30.         if ($subject instanceof ForumReponse) {
  31.             return $this->canManageReponse($subject$user);
  32.         }
  33.         if ($subject instanceof Sujetforum) {
  34.             return $this->canManageSujet($subject$user);
  35.         }
  36.         return false;
  37.     }
  38.     private function canManageReponse(ForumReponse $reponseUser $user): bool
  39.     {
  40.         if ($this->isForumModerator($user)) {
  41.             return true;
  42.         }
  43.         $owner $reponse->getUser();
  44.         return null !== $owner && $owner->getId() === $user->getId();
  45.     }
  46.     private function canManageSujet(Sujetforum $sujetUser $user): bool
  47.     {
  48.         if ($this->isForumModerator($user)) {
  49.             return true;
  50.         }
  51.         $owner $sujet->getUser();
  52.         return null !== $owner && $owner->getId() === $user->getId();
  53.     }
  54.     private function isForumModerator(User $user): bool
  55.     {
  56.         return \in_array('ROLE_ADMIN'$user->getRoles(), true);
  57.     }
  58. }