src/Security/ECommerce/CartVoter.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\Security\ECommerce;
  3. use App\Entity\ECommerce\Cart;
  4. use App\Entity\App\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. /**
  10. * Class CartVoter
  11. *
  12. * @package MDL\ECommerceBundle\Security
  13. */
  14. class CartVoter extends Voter
  15. {
  16. // these strings are just invented: you can use anything
  17. const CREATE = 'CART_CREATE';
  18. const VIEW = 'CART_VIEW';
  19. const EDIT = 'CART_EDIT';
  20. const DELETE = 'CART_DELETE';
  21. /**
  22. * CartVoter constructor.
  23. */
  24. public function __construct(private readonly AccessDecisionManagerInterface $decisionManager)
  25. {
  26. }
  27. /**
  28. * @param string $attribute
  29. * @param mixed $subject
  30. *
  31. * @return bool
  32. */
  33. protected function supports($attribute, $subject)
  34. {
  35. // if the attribute isn't one we support, return false
  36. if (!in_array($attribute, [
  37. self::CREATE,
  38. self::VIEW,
  39. self::EDIT,
  40. self::DELETE,
  41. ])) {
  42. return false;
  43. }
  44. // only vote on Cart objects inside this voter
  45. if (!$subject instanceof Cart && $attribute !== self::CREATE) {
  46. return false;
  47. }
  48. return true;
  49. }
  50. /**
  51. * @param string $attribute
  52. * @param Cart $individualOrder
  53. *
  54. * @return bool
  55. */
  56. protected function voteOnAttribute($attribute, $individualOrder, TokenInterface $token)
  57. {
  58. if ($this->decisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) {
  59. return true;
  60. }
  61. $user = $token->getUser();
  62. if (!$user instanceof UserInterface) {
  63. return false;
  64. }
  65. return match ($attribute) {
  66. self::CREATE => $this->canCreate($user),
  67. self::VIEW => $this->canView($individualOrder, $user),
  68. self::EDIT => $this->canEdit($individualOrder, $user),
  69. self::DELETE => $this->canDelete(),
  70. default => throw new \LogicException('This code should not be reached!'),
  71. };
  72. }
  73. private function canCreate(User $user): bool
  74. {
  75. return !$user->hasRole('ROLE_GUEST');
  76. }
  77. /**
  78. *
  79. * @return bool
  80. */
  81. private function canView(Cart $cart, User $user)
  82. {
  83. return $this->canEdit($cart, $user);
  84. }
  85. /**
  86. *
  87. * @return bool
  88. */
  89. private function canEdit(Cart $cart, UserInterface $user)
  90. {
  91. if (!$cart->isCheckedOut()) {
  92. return $user === $cart->getUser();
  93. }
  94. return false;
  95. }
  96. private function canDelete(): bool
  97. {
  98. return false;
  99. }
  100. }