src/Security/Voter/UserVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. class UserVoter extends Voter
  7. {
  8. public const EDIT = 'USER_EDIT';
  9. public const VIEW = 'USER_VIEW';
  10. protected function supports(string $attribute, $profil): bool
  11. {
  12. // replace with your own logic
  13. // https://symfony.com/doc/current/security/voters.html
  14. return in_array($attribute, [self::EDIT, self::VIEW])
  15. && $profil instanceof \App\Entity\User;
  16. }
  17. protected function voteOnAttribute(string $attribute, $profil, TokenInterface $token): bool
  18. {
  19. $user = $token->getUser();
  20. // if the user is anonymous, do not grant access
  21. if (!$user instanceof UserInterface) {
  22. return false;
  23. }
  24. // ... (check conditions and return true to grant permission) ...
  25. switch ($attribute) {
  26. case self::EDIT:
  27. // logic to determine if the user can EDIT
  28. // return true or false
  29. return $this->canEdit($profil,$user);
  30. break;
  31. case self::VIEW:
  32. // logic to determine if the user can VIEW
  33. // return true or false
  34. return $this->canView($profil,$user);
  35. break;
  36. }
  37. return false;
  38. }
  39. public function canEdit($profil,$user)
  40. {
  41. //Si le user veux consulter son profil
  42. if($user === $profil){
  43. return true;
  44. }
  45. //Si le user veut consulter le profil d'un client
  46. $commandes = $profil->getCommandes();
  47. foreach ($commandes as $key => $commande) {
  48. //Si le client a déjà passé une commande auprès de ce foodtruck
  49. if(in_array($commande->getService()->getFoodtruck(),$user->getFoodtrucks()->toArray())){
  50. return true;
  51. }
  52. }
  53. }
  54. public function canView($profil,$user)
  55. {
  56. //Si le user veux consulter son profil
  57. if($user === $profil){
  58. return true;
  59. }
  60. //Si le user veut consulter le profil d'un client
  61. $commandes = $profil->getCommandes();
  62. foreach ($commandes as $key => $commande) {
  63. //Si le client a déjà passé une commande auprès de ce foodtruck
  64. if(in_array($commande->getService()->getFoodtruck(),$user->getFoodtrucks()->toArray())){
  65. return true;
  66. }
  67. }
  68. }
  69. }