<?php
namespace App\Security\Voter;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ContractManagerVoter extends Voter
{
public const VIEW_CONTRACTS = 'VIEW_CONTRACTS';
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute === self::VIEW_CONTRACTS;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
// Si tiene alguno de estos roles, puede ver contratos
$roles = $user->getRoles();
if (in_array('ROLE_ADMIN', $roles) ||
in_array('ROLE_LEGAL', $roles) ||
in_array('ROLE_CONTRACTS_VIEWER', $roles) ||
in_array('ROLE_FINANCES', $roles)) {
return true;
}
// Verificar si es gestor de algĂșn contrato
return $this->isContractManager($user);
}
private function isContractManager(User $user): bool
{
$qb = $this->entityManager->createQueryBuilder();
$count = $qb
->select('COUNT(sc.id)')
->from('App\Entity\SupplierContract', 'sc')
->leftJoin('sc.managers', 'm')
->leftJoin('sc.administrativeManagers', 'am')
->where('m.id = :userId OR am.id = :userId')
->setParameter('userId', $user->getId())
->getQuery()
->getSingleScalarResult();
return $count > 0;
}
}