<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Repository\ResumeTemplateRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class ResumeVoter extends Voter
{
const CREATE_RESUME = 'create_resume';
private AuthorizationCheckerInterface $authorizationChecker;
private ResumeTemplateRepository $resumeTemplateRepo;
public function __construct(AuthorizationCheckerInterface $authorizationChecker, ResumeTemplateRepository $resumeTemplateRepo)
{
$this->authorizationChecker = $authorizationChecker;
$this->resumeTemplateRepo = $resumeTemplateRepo;
}
protected function supports($attribute, $subject)
{
return in_array($attribute, [
self::CREATE_RESUME,
]);
}
/**
* @param string $attribute
* @param ?\App\Entity\Resume|mixed $subject
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
/** @var User|string $user */
$user = $subject ? $subject->getStudent() : $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::CREATE_RESUME:
return 0 < $user->getResumes()->count() && $this->resumeTemplateRepo->count([]) > 0;
}
return false;
}
}