src/Security/Voter/ContractManagerVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class ContractManagerVoter extends Voter
  8. {
  9. public const VIEW_CONTRACTS = 'VIEW_CONTRACTS';
  10. private EntityManagerInterface $entityManager;
  11. public function __construct(EntityManagerInterface $entityManager)
  12. {
  13. $this->entityManager = $entityManager;
  14. }
  15. protected function supports(string $attribute, mixed $subject): bool
  16. {
  17. return $attribute === self::VIEW_CONTRACTS;
  18. }
  19. protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
  20. {
  21. $user = $token->getUser();
  22. if (!$user instanceof User) {
  23. return false;
  24. }
  25. // Si tiene alguno de estos roles, puede ver contratos
  26. $roles = $user->getRoles();
  27. if (in_array('ROLE_ADMIN', $roles) ||
  28. in_array('ROLE_LEGAL', $roles) ||
  29. in_array('ROLE_CONTRACTS_VIEWER', $roles) ||
  30. in_array('ROLE_FINANCES', $roles)) {
  31. return true;
  32. }
  33. // Verificar si es gestor de algĂșn contrato
  34. return $this->isContractManager($user);
  35. }
  36. private function isContractManager(User $user): bool
  37. {
  38. $qb = $this->entityManager->createQueryBuilder();
  39. $count = $qb
  40. ->select('COUNT(sc.id)')
  41. ->from('App\Entity\SupplierContract', 'sc')
  42. ->leftJoin('sc.managers', 'm')
  43. ->leftJoin('sc.administrativeManagers', 'am')
  44. ->where('m.id = :userId OR am.id = :userId')
  45. ->setParameter('userId', $user->getId())
  46. ->getQuery()
  47. ->getSingleScalarResult();
  48. return $count > 0;
  49. }
  50. }