src/Security/Voter/StaffVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
  4. use App\Entity\Staff;
  5. use App\Entity\User;
  6. use App\Repository\StaffRepository;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. class StaffVoter extends Voter
  12. {
  13.     public const VIEW 'VIEW_STAFF';
  14.     private Security $security;
  15.     private StaffRepository $staffRepository;
  16.     public function __construct(
  17.         Security $security,
  18.         StaffRepository $staffRepository
  19.     ) {
  20.         $this->security $security;
  21.         $this->staffRepository $staffRepository;
  22.     }
  23.     protected function supports(string $attributemixed $subject): bool
  24.     {
  25.         return in_array($attribute, [
  26.                 self::VIEW,
  27.             ])
  28.             && ($subject instanceof Paginator
  29.                 || $subject instanceof Staff)
  30.         ;
  31.     }
  32.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  33.     {
  34.         /**
  35.          * @var User $user
  36.          */
  37.         $user $token->getUser();
  38.         // if the user is anonymous, do not grant access
  39.         if (!$user instanceof UserInterface) {
  40.             return false;
  41.         }
  42.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  43.             return true;
  44.         }
  45.         $userStaff $user->getStaff();
  46.         // TODO this should just be temporary until Api Platform allows security check on the owning side
  47.         if ($subject instanceof Paginator) {
  48.             $query $subject
  49.                 ->getQuery()
  50.             ;
  51.             $queryParameters $query->getParameters();
  52.             $id $queryParameters[0]
  53.                 ->getValue()
  54.             ;
  55.             $staff $this->staffRepository->find($id);
  56.         } else {
  57.             $staff $subject;
  58.         }
  59.         switch ($attribute) {
  60.             case self::VIEW:
  61.                 return $userStaff
  62.                     && $userStaff->getId() === $staff->getId();
  63.         }
  64.         return false;
  65.     }
  66. }