<?php
namespace App\Security;
use App\Entity\Applicant;
use App\Entity\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ApplicantVoter extends Voter
{
// these strings are just invented: you can use anything
public const VIEW = 'view';
public const EDIT = 'edit';
/**
* @param string $attribute
* @param mixed $subject
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!\in_array($attribute, [self::VIEW, self::EDIT], true)) {
return false;
}
// only vote on Vacancy objects inside this voter
if (!$subject instanceof Applicant) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
*/
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;
}
// you know $subject is a Applicant object, thanks to supports
/** @var Applicant $applicant */
$applicant = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($applicant, $user);
case self::EDIT:
return $this->canEdit($applicant, $user);
}
throw new LogicException('This code should not be reached!');
}
private function canView(Applicant $applicant, User $user): bool
{
// if they can edit, they can view
if ($this->canEdit($applicant, $user)) {
return true;
}
if ($user->hasRole('ROLE_ADMIN_USER') || $user->isSuperAdmin()) {
return true;
}
if ($user->hasRole('ROLE_ADMIN_HIRING_MANAGER')) {
if ($applicant->getVacancy()->getManagers()->count() && $user->getCompanies()->isEmpty()) {
return $applicant->getVacancy()->getManagers()->contains($user);
}
if ($user->getCompanies()->contains($applicant->getVacancy()->getCompany())) {
return true;
}
}
if ($user->hasRole('ROLE_ADMIN_JOB_OWNER')) {
if ($applicant->getVacancy()
&& $applicant->getVacancy()->getManagers()->count()
&& $applicant->getVacancy()->getManagers()->contains($user)
) {
return true;
}
if ($applicant->getVacancy() && $user->getCompanies()->contains($applicant->getVacancy()->getCompany())) {
return true;
}
}
return false;
}
private function canEdit(Applicant $applicant, User $user): bool
{
return false;
}
}