src/Security/Voters/CalendarVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\Calendar;
  4. use App\Entity\OperatoreUser;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class CalendarVoter 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 the attribute isn't one we support, return false
  21.     if (!in_array($attribute, [self::EDITself::DELETE])) {
  22.       return false;
  23.     }
  24.     // only vote on `Calendar` objects
  25.     if ($subject && !$subject instanceof Calendar) {
  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.       // the user must be logged in; if not, deny access
  35.       return false;
  36.     }
  37.     // you know $subject is a Calendar object, thanks to `supports()`
  38.     /** @var Calendar $calendar */
  39.     $calendar $subject;
  40.     switch ($attribute) {
  41.       case self::EDIT:
  42.         return $this->canEdit($calendar$user);
  43.       case self::DELETE:
  44.         return $this->canDelete($calendar$user);
  45.     }
  46.     throw new \LogicException('This code should not be reached!');
  47.   }
  48.   private function canEdit(Calendar $calendarUser $user)
  49.   {
  50.     if ($this->security->isGranted('ROLE_ADMIN')) {
  51.       return true;
  52.     }
  53.     if ($this->security->isGranted('ROLE_OPERATORE')) {
  54.       /** @var OperatoreUser $user */
  55.       if ($user->getId() === $calendar->getOwnerId() || in_array($user->getId(), $calendar->getModeratorsId())) {
  56.         return true;
  57.       }
  58.     }
  59.     return false;
  60.   }
  61.   private function canDelete(Calendar $calendarUser $user)
  62.   {
  63.     if ($this->security->isGranted('ROLE_ADMIN')) {
  64.       return true;
  65.     }
  66.     if ($this->security->isGranted('ROLE_OPERATORE')) {
  67.       /** @var OperatoreUser $user */
  68.       if ($user->getId() === $calendar->getOwnerId()) {
  69.         return true;
  70.       }
  71.     }
  72.     return false;
  73.   }
  74. }