src/Security/Voter/EventVoter.php line 13

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