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

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