src/Security/MalletteFileVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\MalletteFile;
  4. use App\Entity\Security\AppUser;
  5. use App\Repository\MalletteFileRepository;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class MalletteFileVoter extends Voter
  9. {
  10.     public const VIEW 'view';
  11.     public const DOWNLOAD 'download';
  12.     /** @var null|array<int> */
  13.     private ?array $cachedAccessibleFileIds null;
  14.     private ?int $cachedUserId null;
  15.     public function __construct(
  16.         private MalletteFileRepository $malletteFileRepository,
  17.     ) {
  18.     }
  19.     protected function supports(string $attribute$subject): bool
  20.     {
  21.         if (!in_array($attribute, [self::VIEWself::DOWNLOAD])) {
  22.             return false;
  23.         }
  24.         return $subject instanceof MalletteFile;
  25.     }
  26.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  27.     {
  28.         if (!in_array($attribute, [self::VIEWself::DOWNLOAD])) {
  29.             return false;
  30.         }
  31.         $user $token->getUser();
  32.         // the user must be logged in; if not, deny access
  33.         if (!$user instanceof AppUser) {
  34.             return false;
  35.         }
  36.         if ($this->cachedUserId !== $user->getId() || $this->cachedAccessibleFileIds === null) {
  37.             $groups $user->getClient()->getGroups();
  38.             $malletteFiles $this->malletteFileRepository->findByCategoryAccess($groups$user);
  39.             $this->cachedAccessibleFileIds array_map(fn ($file) => $file->getId(), $malletteFiles);
  40.             $this->cachedUserId $user->getId();
  41.         }
  42.         return in_array($subject->getId(), $this->cachedAccessibleFileIdstrue);
  43.     }
  44. }