src/Security/Voter/AttachmentVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Attachment;
  4. use App\Entity\Project;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class AttachmentVoter extends Voter
  9. {
  10.     public const EDITABLE 'IS_EDITABLE';
  11.     public const OWNER 'IS_OWNER';
  12. //    public const VIEW = 'POST_VIEW';
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         // replace with your own logic
  16.         // https://symfony.com/doc/current/security/voters.html
  17.         return in_array($attribute, [self::EDITABLEself::OWNER])
  18.             && $subject instanceof Attachment;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         // if the user is anonymous, do not grant access
  24.         if (!$user instanceof UserInterface) {
  25.             return false;
  26.         }
  27.         if (!$subject instanceof Attachment) {
  28.             throw new \Exception('Wrong type somehow passed');
  29.         }
  30.         // ... (check conditions and return true to grant permission) ...
  31.         switch ($attribute) {
  32.             case self::EDITABLE:
  33.                 $application $subject->getProject()->getApplication();
  34.                 return $application->isActive() && $application->isOpen() && $application->getDistrict()->getUser()->contains($user);
  35.                 break;
  36.             case self::OWNER:
  37.                 return $subject->getProject()->getApplication()->getDistrict()->getUser()->contains($user);
  38.                 break;
  39.         }
  40.         return false;
  41.     }
  42. }