<?php
namespace App\Security\Voter;
use App\Entity\Gos\Consultant\ConsultantSettings;
use App\Entity\Gos\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ConsultantVoter extends Voter
{
public const IS_CONSULTANT = 'is_consultant';
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
protected function supports($attribute, $subject): bool
{
return $attribute === self::IS_CONSULTANT;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case self::IS_CONSULTANT:
return $this->isConsultant($user);
}
throw new \LogicException('This code should not be reached!');
}
private function isConsultant(User $user): bool
{
$consultantSettings = $this->em->getRepository(ConsultantSettings::class)->findSettings();
$consultants = $consultantSettings->getConsultants()->toArray();
return $user->hasRole('ROLE_SUPER_CONSULTANT') || in_array($user, $consultants, true);
}
}