src/Security/Voter/CommandeVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Entity\Commande;
  5. use Symfony\Component\Security\Core\Security;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. class CommandeVoter extends Voter
  10. {
  11. public const EDIT = 'COMMANDE_EDIT';
  12. public const VIEW = 'COMMANDE_VIEW';
  13. public const DELETE = 'COMMANDE_DELETE';
  14. private $security;
  15. public function __construct(Security $security)
  16. {
  17. $this->security = $security;
  18. }
  19. protected function supports(string $attribute, $commande): bool
  20. {
  21. // replace with your own logic
  22. // https://symfony.com/doc/current/security/voters.html
  23. return in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])
  24. && $commande instanceof \App\Entity\Commande;
  25. }
  26. protected function voteOnAttribute(string $attribute, $commande, TokenInterface $token): bool
  27. {
  28. $user = $token->getUser();
  29. // if the user is anonymous, do not grant access
  30. if (!$user instanceof UserInterface) {
  31. return false;
  32. }
  33. //On vérifie si l'utilisateur est admin
  34. if($this->security->isGranted('ROLE_ADMIN'))
  35. {
  36. return true;
  37. }
  38. // ... (check conditions and return true to grant permission) ...
  39. switch ($attribute) {
  40. case self::EDIT:
  41. // on vérifie si on peut éditer
  42. return $this->canEdit($commande, $user);
  43. break;
  44. case self::VIEW:
  45. // on vérifie si on peut visualiser
  46. return $this->canView($commande, $user);
  47. break;
  48. case self::DELETE:
  49. // on vérifie si on peut supprimer
  50. return $this->canDelete($commande, $user);
  51. break;
  52. }
  53. return false;
  54. }
  55. public function canEdit(Commande $commande, User $user)
  56. {
  57. if($this->security->isGranted('ROLE_FOODTRUCK'))
  58. {
  59. return in_array($commande->getService()->getFoodtruck(), $user->getFoodtrucks()->toArray());
  60. }
  61. return false;
  62. }
  63. public function canView(Commande $commande, User $user)
  64. {
  65. if($this->security->isGranted('ROLE_FOODTRUCK'))
  66. {
  67. return in_array($commande->getService()->getFoodtruck(), $user->getFoodtrucks()->toArray());
  68. }
  69. if($this->security->isGranted('ROLE_USER'))
  70. {
  71. return $user === $commande->getUser();
  72. }
  73. return false;
  74. }
  75. public function canDelete(Commande $commande, User $user)
  76. {
  77. if($this->security->isGranted('ROLE_FOODTRUCK'))
  78. {
  79. return in_array($commande->getService()->getFoodtruck(), $user->getFoodtrucks()->toArray());
  80. }
  81. return false;
  82. }
  83. }