src/Security/Voter/BlogCommentVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\BlogComment;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class BlogCommentVoter extends Voter
  10. {
  11.     const EDIT   'edit';
  12.     const DELETE 'delete';
  13.     private $security;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.     }
  18.     protected function supports($attribute$subject)
  19.     {
  20.         if (!in_array($attribute, [self::EDITself::DELETE])) {
  21.             return false;
  22.         }
  23.         if (!$subject instanceof BlogComment) {
  24.             return false;
  25.         }
  26.         return true;
  27.     }
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  29.     {
  30.         $user $token->getUser();
  31.         if (!$user instanceof User) {
  32.             return false;
  33.         }
  34.         /** @var BlogComment $comment */
  35.         $comment $subject;
  36.         if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
  37.             return true;
  38.         }
  39.         switch ($attribute) {
  40.             case self::EDIT:
  41.                 return $this->canEditOrDelete($comment$user$token);
  42.             case self::DELETE:
  43.                 return $this->canEditOrDelete($comment$user$token);
  44.         }
  45.         throw new \LogicException('This code should not be reached!');
  46.     }
  47.     private function canEditOrDelete(BlogComment $commentUser $userTokenInterface $token)
  48.     {
  49.         return $comment->getUser() === $user || $this->security->isGranted(User::ROLE_NEWS_ADMIN);
  50.     }
  51. }