src/Security/Voters/MessageVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\Message;
  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 MessageVoter extends Voter
  10. {
  11.   const EDIT 'edit';
  12.   const VIEW 'view';
  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::VIEW])) {
  22.       return false;
  23.     }
  24.     // only vote on `Message` objects
  25.     if ($subject && !$subject instanceof Message) {
  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 Message object, thanks to `supports()`
  38.     /** @var Message $message */
  39.     $message $subject;
  40.     switch ($attribute) {
  41.       case self::EDIT:
  42.         return $this->canEdit($message$user);
  43.       case self::VIEW:
  44.         return $this->canView($message$user);
  45.     }
  46.     throw new \LogicException('This code should not be reached!');
  47.   }
  48.   private function canView(Message $messageUser $user)
  49.   {
  50.     $pratica $message->getApplication();
  51.     // if they can edit, they can view
  52.     if ($this->canEdit($message$user)) {
  53.       return true;
  54.     }
  55.     return $user === $pratica->getUser();
  56.   }
  57.   private function canEdit(Message $messageUser $user)
  58.   {
  59.     $pratica $message->getApplication();
  60.     if ($this->security->isGranted('ROLE_ADMIN')) {
  61.       return true;
  62.     }
  63.     if ($this->security->isGranted('ROLE_OPERATORE')) {
  64.       /** @var OperatoreUser $user */
  65.       if (in_array($pratica->getServizio()->getId(), $user->getServiziAbilitati()->toArray())) {
  66.         return true;
  67.       }
  68.     }
  69.     return false;
  70.   }
  71. }