Files
myep-team/src/Security/Voter/AssignmentVoter.php
T

96 lines
3.2 KiB
PHP

<?php
namespace App\Security\Voter;
use App\Entity\Application;
use App\Entity\Assignment;
use App\Entity\Disposition;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class AssignmentVoter extends Voter
{
public const VIEW = 'VIEW';
public const EDIT = 'EDIT';
public const APPLY = 'APPLY';
public const PUBLISH = 'PUBLISH';
public const CALL_OFF = 'CALL_OFF';
public function __construct(
private readonly Security $security,
private readonly EntityManagerInterface $entityManager
) {
}
protected function supports(string $attribute, mixed $subject): bool
{
if (!$subject instanceof Assignment) {
return false;
}
return in_array($attribute, [static::VIEW, static::EDIT, static::APPLY, static::PUBLISH, static::CALL_OFF]);
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
/** @var Assignment $assignment */
$assignment = $subject;
// All authenticated users may view assignments
if (static::VIEW === $attribute && null !== $token->getUser()) {
return true;
}
// Only users with administrative role may edit assignments
if (static::EDIT === $attribute) {
return $this->security->isGranted('ROLE_ADMINISTRATIVE');
}
// Only users with administrative role may publish assignments currently in draft
if (static::PUBLISH === $attribute) {
return Assignment::STATUS_DRAFT === $assignment->getStatus()
&& $this->security->isGranted('ROLE_ADMINISTRATIVE');
}
// Only users with administrative role may call off assignments
if (static::CALL_OFF === $attribute) {
return Assignment::STATUS_CALLED_OFF !== $assignment->getStatus()
&& $this->security->isGranted('ROLE_ADMINISTRATIVE');
}
// Only allow applications to published, not deleted and not called off assignments
if (
true === in_array($assignment->getStatus(), [
Assignment::STATUS_DRAFT,
Assignment::STATUS_DELETED,
Assignment::STATUS_CALLED_OFF,
])) {
return false;
}
// Only allow applications on empty slots
$availableSlots = (int) $assignment->getAvailableDispositions();
if (0 < $availableSlots) {
return $assignment->getDispositions()->count() < $availableSlots;
}
// Only teamers without existing applications may apply to the assignment
if ($this->security->isGranted('ROLE_TEAMER')) {
/** @var User $user */
$user = $token->getUser();
$teamer = $user->getTeamer();
$application = $this
->entityManager
->getRepository(Application::class)
->findOneBy(['teamer' => $teamer, 'assignment' => $assignment]);
return null === $application;
}
return false;
}
}