src/Security/DocumentVoter.php line 11

  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Document;
  4. use App\Entity\DocumentPermission;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class DocumentVoter extends Voter {
  9.     const VIEW 'view';
  10.     const EDIT 'edit';
  11.     protected function supports(string $attribute$subject): bool
  12.     {
  13.         // if the attribute isn't one we support, return false
  14.         if (!in_array($attribute, [self::VIEWself::EDIT])) {
  15.             return false;
  16.         }
  17.         // only vote on "Document" objects
  18.         if(!$subject instanceof Document) {
  19.             return false;
  20.         }
  21.         return true;
  22.     }
  23.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  24.     {
  25.         $user $token->getUser();
  26.         if(!$user instanceof User) {
  27.             return false;
  28.         }
  29.         /** @var Document $document */
  30.         $document $subject;
  31.         switch ($attribute) {
  32.             case self::VIEW:
  33.                 return $this->canView($document$user);
  34.             case self::EDIT:
  35.                 return $this->canEdit($document$user);
  36.             default:
  37.                 throw new \LogicException('This code should not be reached');
  38.         }
  39.     }
  40.     private function canView(Document $documentUser $user) {
  41.         if($this->canEdit($document$user))
  42.             return true;
  43.         return false;
  44.     }
  45.     private function canEdit(Document $documentUser $user) {
  46.         /** @var DocumentPermission $permission */
  47.         foreach($document->getDocumentPermissions() as $permission) {
  48.             if($user === $permission->getUser())
  49.                 return true;
  50.         }
  51.             return $user === $document->getOwner();
  52.     }
  53. }