src/Security/Voters/FolderVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\Folder;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class FolderVoter extends Voter
  9. {
  10.   const EDIT 'edit';
  11.   const VIEW 'view';
  12.   private $security;
  13.   public function __construct(Security $security)
  14.   {
  15.     $this->security $security;
  16.   }
  17.   protected function supports($attribute$subject): bool
  18.   {
  19.     // if the attribute isn't one we support, return false
  20.     if (!in_array($attribute, [self::EDITself::VIEW])) {
  21.       return false;
  22.     }
  23.     // only vote on `Folder` objects
  24.     if ($subject && !$subject instanceof Folder) {
  25.       return false;
  26.     }
  27.     return true;
  28.   }
  29.   protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  30.   {
  31.     $user $token->getUser();
  32.     if (!$user instanceof User) {
  33.       // the user must be logged in; if not, deny access
  34.       return false;
  35.     }
  36.     // you know $subject is a Folder object, thanks to `supports()`
  37.     /** @var Folder $folder */
  38.     $folder $subject;
  39.     switch ($attribute) {
  40.       case self::EDIT:
  41.         return $this->canEdit($folder$user);
  42.       case self::VIEW:
  43.         return $this->canView($folder$user);
  44.     }
  45.     throw new \LogicException('This code should not be reached!');
  46.   }
  47.   private function canView(Folder $folderUser $user): bool
  48.   {
  49.     // if they can edit, they can view
  50.     if ($this->canEdit($folder$user)) {
  51.       return true;
  52.     }
  53.     return $user->getId() == $folder->getOwnerId();
  54.   }
  55.   private function canEdit(Folder $folderUser $user): bool
  56.   {
  57.     if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_OPERATORE')) {
  58.       return true;
  59.     }
  60.     return false;
  61.   }
  62. }