src/Security/Voters/UploadsVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\Upload;
  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 UploadsVoter extends Voter
  9. {
  10.     private Security $security;
  11.     public const CAN_UPLOAD   'upload.can.be.uploaded';
  12.     public const CAN_DOWNLOAD 'upload.can.be.downloaded';
  13.     public const CAN_EDIT 'upload.can.be.edited';
  14.     public const CAN_PUBLIC 'upload.can.be.public';
  15.     private const ATTRIBUTES = [
  16.         self::CAN_UPLOAD,
  17.         self::CAN_DOWNLOAD,
  18.         self::CAN_EDIT,
  19.         self::CAN_PUBLIC,
  20.     ];
  21.     public function __construct(Security $security)
  22.     {
  23.         $this->security $security;
  24.     }
  25.     protected function supports($attribute$subject): bool
  26.     {
  27.         return in_array($attributeself::ATTRIBUTES);
  28.     }
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  30.     {
  31.         $user $token->getUser();
  32.         switch ($attribute) {
  33.             case self::CAN_UPLOAD:
  34.             case self::CAN_DOWNLOAD:
  35.             case self::CAN_EDIT:
  36.                 return $this->hasAccess($subject);
  37.             case self::CAN_PUBLIC:
  38.                 return $this->canPublic($subject);
  39.         }
  40.         throw new \LogicException('Invalid attribute: ' $attribute);
  41.     }
  42.     private function hasAccess(Upload $upload): bool
  43.     {
  44.         if ($upload->getIsDeleted()) {
  45.             return false;
  46.         }
  47.         if ( in_array('ANON_USER'$upload->getAccessControl()) ) {
  48.             return true;
  49.         }
  50.         if ( in_array('MF_PROFILE'$upload->getAccessControl()) && $this->security->isGranted('user.is_manufacturer')) {
  51.             return true;
  52.         }
  53.         if ($this->security->getUser() && array_intersect($this->security->getUser()->getRoles(), $upload->getAccessControl())) {
  54.             return true;
  55.         }
  56.         return false;
  57.     }
  58.     private function canPublic(Upload $upload): bool
  59.     {
  60.         if ($upload->getIsDeleted()) {
  61.             return false;
  62.         }
  63.         if ( in_array('ANON_USER'$upload->getAccessControl()) ) {
  64.             return true;
  65.         }
  66.         return false;
  67.     }
  68. }