<?php
namespace App\Security\Voter;
use App\Entity\TranscriptOfRecords;
use App\Entity\User;
use App\HeiAdministration\StaffDirectory;
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 TranscriptOfRecordsVoter extends Voter
{
public const VIEW = 'TOR_VIEW';
public const CREATE = 'TOR_CREATE';
public const MODIFY = 'TOR_MODIFY';
private Security $security;
private StaffDirectory $staffDirectory;
public function __construct(
Security $security,
StaffDirectory $staffDirectory,
) {
$this->security = $security;
$this->staffDirectory = $staffDirectory;
}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [
self::VIEW,
self::CREATE,
self::MODIFY,
])
&& $subject instanceof TranscriptOfRecords
;
}
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;
}
$student = $user->getStudent();
$isCorrectStudent = null !== $student && $subject->getStudent() === $student;
switch ($attribute) {
case self::VIEW:
return
$this->staffDirectory->isStaffAtSendingHei($user, $subject)
|| $this->staffDirectory->isStaffAtReceivingHei($user, $subject)
|| (
$isCorrectStudent
);
case self::CREATE:
case self::MODIFY:
return $this->staffDirectory->isStaffAtReceivingHei($user, $subject);
}
return false;
}
}