<?php
namespace PaperKite\Common\Security\Voter;
use PaperKite\Common\Service\InquiryService;
use PaperKite\EmployeeApi\Entity\EmployeeInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class InquiryVoter extends Voter
{
public const EDIT = 'INQUIRY_EDIT';
public const VIEW = 'INQUIRY_VIEW';
public function __construct(
private Security $security,
private InquiryService $inquiryService,
) {
}
protected function supports(string $attribute, $subject): bool
{
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [
self::EDIT,
self::VIEW,
]);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var EmployeeInterface $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
$inquiry = $this->inquiryService->getById($user, $subject);
return self::EDIT === $attribute && $inquiry->getEmployee() === $user->getUserIdentifier();
}
}