vendor/crea/security-bundle/src/Voter/UserGroupVoter.php line 16

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Crea\SecurityBundle\Voter;
  4. use Crea\SecurityBundle\Entity\User;
  5. use Crea\SecurityBundle\Entity\UserGroup;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. /**
  10. * @extends Voter<string, UserGroup>
  11. */
  12. class UserGroupVoter extends Voter
  13. {
  14. public const USER_GROUP_LIST = 'SECURITY_USER_GROUP_LIST';
  15. public const USER_GROUP_CREATE = 'SECURITY_USER_GROUP_CREATE';
  16. public const USER_GROUP_UPDATE = 'SECURITY_USER_GROUP_UPDATE';
  17. public const USER_GROUP_REMOVE = 'SECURITY_USER_GROUP_REMOVE';
  18. protected function supports($attribute, $subject): bool
  19. {
  20. return in_array($attribute, [
  21. self::USER_GROUP_LIST,
  22. self::USER_GROUP_CREATE,
  23. self::USER_GROUP_UPDATE,
  24. self::USER_GROUP_REMOVE,
  25. ]) && (null === $subject || $subject instanceof UserGroup);
  26. }
  27. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  28. {
  29. /** @var User $loggedUser */
  30. $loggedUser = $token->getUser();
  31. if (!$loggedUser instanceof UserInterface) {
  32. return false;
  33. }
  34. switch ($attribute) {
  35. case self::USER_GROUP_LIST:
  36. return $this->voteOnList($loggedUser);
  37. case self::USER_GROUP_CREATE:
  38. return $this->voteOnCreate($loggedUser);
  39. case self::USER_GROUP_UPDATE:
  40. return $this->voteOnUpdate($subject, $loggedUser);
  41. case self::USER_GROUP_REMOVE:
  42. return $this->voteOnRemove($subject, $loggedUser);
  43. }
  44. return false;
  45. }
  46. private function voteOnList(UserInterface $loggedUser): bool
  47. {
  48. if (in_array(self::USER_GROUP_LIST, $loggedUser->getRoles())) {
  49. return true;
  50. }
  51. return false;
  52. }
  53. private function voteOnCreate(UserInterface $loggedUser): bool
  54. {
  55. if (in_array(self::USER_GROUP_CREATE, $loggedUser->getRoles())) {
  56. return true;
  57. }
  58. return false;
  59. }
  60. private function voteOnUpdate(?UserGroup $subject, User $loggedUser): bool
  61. {
  62. if (!in_array(self::USER_GROUP_UPDATE, $loggedUser->getRoles())) {
  63. return false;
  64. }
  65. if (null === $subject) {
  66. return true;
  67. }
  68. if (in_array('ROLE_ADMIN', $loggedUser->getRoles())) {
  69. return true;
  70. }
  71. return false;
  72. }
  73. private function voteOnRemove(?UserGroup $subject, User $loggedUser): bool
  74. {
  75. if (!in_array(self::USER_GROUP_REMOVE, $loggedUser->getRoles())) {
  76. return false;
  77. }
  78. if (null === $subject) {
  79. return true;
  80. }
  81. if (in_array('ROLE_ADMIN', $loggedUser->getRoles())) {
  82. return true;
  83. }
  84. return false;
  85. }
  86. }