src/Security/ECommerce/InvoiceVoter.php line 16

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