src/Common/Security/Voter/InquiryVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace PaperKite\Common\Security\Voter;
  3. use Lightbulb\Symfony\Exception\NotFoundException;
  4. use PaperKite\Common\Service\InquiryReaderService;
  5. use PaperKite\EmployeeApi\Entity\EmployeeInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class InquiryVoter extends Voter
  11. {
  12.     public const EDIT 'INQUIRY_EDIT';
  13.     public const VIEW 'INQUIRY_VIEW';
  14.     public function __construct(
  15.         private Security $security,
  16.         private InquiryReaderService $inquiryReaderService,
  17.     ) {
  18.     }
  19.     protected function supports(string $attribute$subject): bool
  20.     {
  21.         // https://symfony.com/doc/current/security/voters.html
  22.         return in_array($attribute, [
  23.             self::EDIT,
  24.             self::VIEW,
  25.         ]);
  26.     }
  27.     /**
  28.      * @throws NotFoundException
  29.      */
  30.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  31.     {
  32.         /** @var EmployeeInterface $user */
  33.         $user $token->getUser();
  34.         // if the user is anonymous, do not grant access
  35.         if (!$user instanceof UserInterface) {
  36.             return false;
  37.         }
  38.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  39.             return true;
  40.         }
  41.         $inquiry $this->inquiryReaderService->getByGedId($subject);
  42.         return self::EDIT === $attribute && $inquiry->getAssignedEmployee() === $user;
  43.     }
  44. }