src/Security/Voter/Api/FileVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Api;
  3. use App\Entity\File;
  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\User\UserInterface;
  8. class FileVoter extends Voter
  9. {
  10.     public const VIEW 'view';
  11.     public const EDIT 'edit';
  12.     public const DOWNLOAD 'download';
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         return in_array($attribute, [self::VIEWself::EDITself::DOWNLOAD])
  16.             && $subject instanceof File;
  17.     }
  18.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  19.     {
  20.         /** @var User $user */
  21.         $user $token->getUser();
  22.         if (!$user instanceof UserInterface) {
  23.             return false;
  24.         }
  25.         return match ($attribute) {
  26.             self::VIEWself::EDIT => $subject->getOwner() === $user->getProfile(),
  27.             self::DOWNLOAD => $this->canDownload($subject$user),
  28.             default => false,
  29.         };
  30.     }
  31.     private function canDownload(
  32.         File $subject,
  33.         User $user
  34.     ) {
  35.         if (in_array("ROLE_COACH"$user->getRoles())){
  36.             $obj $user->getProfile()->getCoach();
  37.         }
  38.         $company array_filter($obj?->getCompanies()->toArray(), function ($companie) use ($subject){
  39.            return $companie->getKBIS()->getId() === $subject->getId();
  40.         });
  41.         return match (true){
  42.             $obj?->getAPADiploma()?->getId() === $subject->getId() => true,
  43.             $obj?->getSAPDiploma()?->getId() === $subject->getId() => true,
  44.             !empty($company) => true,
  45.             default => false,
  46.         };
  47.     }
  48. }