<?php
namespace App\Security\Voter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Entity\Staff;
use App\Entity\User;
use App\Repository\StaffRepository;
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 StaffVoter extends Voter
{
public const VIEW = 'VIEW_STAFF';
private Security $security;
private StaffRepository $staffRepository;
public function __construct(
Security $security,
StaffRepository $staffRepository
) {
$this->security = $security;
$this->staffRepository = $staffRepository;
}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [
self::VIEW,
])
&& ($subject instanceof Paginator
|| $subject instanceof Staff)
;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
/**
* @var User $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;
}
$userStaff = $user->getStaff();
// TODO this should just be temporary until Api Platform allows security check on the owning side
if ($subject instanceof Paginator) {
$query = $subject
->getQuery()
;
$queryParameters = $query->getParameters();
$id = $queryParameters[0]
->getValue()
;
$staff = $this->staffRepository->find($id);
} else {
$staff = $subject;
}
switch ($attribute) {
case self::VIEW:
return $userStaff
&& $userStaff->getId() === $staff->getId();
}
return false;
}
}