<?php
namespace App\Security\Voter\Scholar\Front;
use App\Entity\Scholar\Lesson\Lesson;
use App\Entity\Scholar\Module\Module;
use App\Entity\Scholar\Training\Training;
use App\Service\Scholar\ScholarNavigationSecurityService;
use Nellapp\Bundle\SDKBundle\Auth\Entity\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class LessonVoter extends Voter
{
public function __construct(
private ScholarNavigationSecurityService $scholarNavigationSecurityService,
)
{
}
private function isSubjectValid($subject): bool
{
if (!is_array($subject)) {
return false;
}
if (
!array_key_exists('training', $subject)
|| !array_key_exists('module', $subject)
|| !array_key_exists('lesson', $subject)
) {
return false;
}
$training = $subject['training'];
$module = $subject['module'];
$lesson = $subject['lesson'];
return $training instanceof Training && $module instanceof Module && $lesson instanceof Lesson;
}
public function supportsAttribute(string $attribute): bool
{
return str_starts_with($attribute, 'FRONT_ACCESS');
}
public function supportsType(string $subjectType): bool
{
return $subjectType === 'array';
}
protected function supports(string $attribute, $subject): bool
{
return $this->isSubjectValid($subject) && $this->supportsAttribute($attribute);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($attribute === 'FRONT_ACCESS') {
return $this->scholarNavigationSecurityService->canAccessLesson(
$subject['training'],
$subject['module'],
$subject['lesson'],
);
}
if ($attribute === 'FRONT_ACCESS_REVIEW') {
return $this->scholarNavigationSecurityService->canAccessLessonReview(
$subject['training'],
$subject['module'],
$subject['lesson'],
);
}
return false;
}
}