<?php
namespace App\Security\Core;
use App\Entity\User\User;
use App\Services\Core\TextbookVoterService;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class TextbookVoter extends Voter
{
const CAN_STUDENT_ACCESS = 'canStudentAccess';
const CAN_TEACHER_ACCESS = 'canTeacherAccess';
private $service;
public function __construct(TextbookVoterService $service)
{
$this->service = $service;
}
/**
* @inheritDoc
*/
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [self::CAN_STUDENT_ACCESS, self::CAN_TEACHER_ACCESS]);
// && $subject instanceof Textbook;
// Adding the Textbook class check in order to have this Voter considered seems to be correct - but "if it ain't broke don't fix it"
// Leaving it here for now to help in debugging potential access issues
}
/**
* @inheritDoc
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
/* The user must be logged in; if not, deny access */
return false;
}
switch ($attribute) {
case self::CAN_STUDENT_ACCESS:
return $this->service->canStudentAccess($user);
case self::CAN_TEACHER_ACCESS:
return $this->service->canTeacherAccess($user);
default:
return false;
}
}
}