<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\DBAL\Types\RoleEnumType;
use App\Entity\Lesson;
use App\Entity\User;
use App\Service\DutyService;
use App\Service\HelpQuestionService;
use DateTimeImmutable;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class HelpQuestionVoter extends Voter
{
public const WRITE_QUESTION = 'WRITE_HELP_QUESTION';
public const READ_LIST = 'READ_HELP_LIST';
private const ACCESSED_ROLES = [
RoleEnumType::ROLE_CURATOR,
RoleEnumType::ROLE_MODERATOR,
RoleEnumType::ROLE_SUPER_ADMIN,
RoleEnumType::ROLE_ADMIN,
];
private HelpQuestionService $helpQuestionService;
private DutyService $dutyService;
public function __construct(HelpQuestionService $helpQuestionService, DutyService $dutyService)
{
$this->helpQuestionService = $helpQuestionService;
$this->dutyService = $dutyService;
}
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [self::WRITE_QUESTION, self::READ_LIST])
&& $subject instanceof Lesson;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
foreach (self::ACCESSED_ROLES as $role) {
if ($user->hasRole($role)) {
return true;
}
}
$helpQuestionDisabledUntilDate = DateTimeImmutable::createFromFormat('Y-m-d', $_ENV['OPTION_HELP_QUESTION_DISABLED_UNTIL_DATE']);
switch ($attribute) {
case self::READ_LIST:
return $this->helpQuestionService->userHasAccessToHelpQuestion($user, $subject);
case self::WRITE_QUESTION:
return $this->helpQuestionService->userHasAccessToHelpQuestion($user, $subject)
&& $user->hasCuratorSupportsInRocket()
&& $this->dutyService->issetDutyCurators()
&& $helpQuestionDisabledUntilDate < $now = new DateTimeImmutable();
}
return false;
}
}