src/Security/Voter/EnrollmentVoter.php line 13
<?php
namespace App\Security\Voter;
use App\Entity\Enrollment;
use App\Enum\RoleType;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @extends Voter<string, Enrollment>
*/
class EnrollmentVoter extends Voter
{
public const EDIT = 'ENROLLMENT_EDIT';
public const NEW = 'ENROLLMENT_NEW';
public const VIEW = 'ENROLLMENT_VIEW';
public const INDEX = 'ENROLLMENT_INDEX';
public const SUBMIT = 'ENROLLMENT_SUBMIT';
public const APPROVE = 'ENROLLMENT_APPROVE';
public const RENEW = 'ENROLLMENT_RENEW';
public function __construct(private readonly Security $security)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
if ($subject !== null) {
return in_array($attribute, [self::EDIT, self::INDEX, self::VIEW, self::SUBMIT, self::APPROVE, self::RENEW])
&& $subject instanceof Enrollment;
} else {
return in_array($attribute, [
self::EDIT,
self::INDEX,
self::VIEW,
self::SUBMIT,
self::APPROVE,
self::RENEW
]);
}
}
/**
* @param mixed $subject is the Enrollment
* @throws NonUniqueResultException
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
return match ($attribute) {
// Who can view a certain enrollment and edit it:
// Who can create and approve a new enrollment manually:
'ENROLLMENT_VIEW', 'ENROLLMENT_EDIT', 'ENROLLMENT_NEW', 'ENROLLMENT_APPROVE' =>
$this->security->isGranted(RoleType::ROLE_PEDAGOGICAL_DIRECTOR) ||
$this->security->isGranted(RoleType::ROLE_FINANCIAL_DIRECTOR) ||
$this->security->isGranted(RoleType::ROLE_EMPLOYEE),
// Who can view the list of enrollments:
'ENROLLMENT_INDEX' =>
$this->security->isGranted(RoleType::ROLE_PEDAGOGICAL_DIRECTOR) ||
$this->security->isGranted(RoleType::ROLE_FINANCIAL_DIRECTOR) ||
$this->security->isGranted(RoleType::ROLE_EMPLOYEE) ||
$this->security->isGranted(RoleType::ROLE_GUARDIAN),
// Who can submit an enrollment:
'ENROLLMENT_SUBMIT' =>
$this->security->isGranted(RoleType::ROLE_EMPLOYEE),
// Who can renew an enrollment:
'ENROLLMENT_RENEW' =>
$this->security->isGranted(RoleType::ROLE_EMPLOYEE) ||
($this->security->isGranted(RoleType::ROLE_GUARDIAN) &&
$subject->getGuardian()->getUser()
=== $user), // Guardian(user) who submitted the enrollment
default => false,
};
}
}