src/App/Security/ProfileVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Profile;
  4. use App\Entity\User;
  5. use LogicException;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ProfileVoter extends Voter
  9. {
  10. // these strings are just invented: you can use anything
  11. public const USER_CAN_VIEW_PROFILE = 'view';
  12. public const USER_CAN_EDIT_PROFILE = 'edit';
  13. public const USER_CAN_ACT_ON_BEHALF_OF_PROFILE = 'act_on_behalf_of';
  14. protected function supports($attribute, $subject)
  15. {
  16. // if the attribute isn't one we support, return false
  17. if (!in_array($attribute, [self::USER_CAN_VIEW_PROFILE, self::USER_CAN_EDIT_PROFILE, self::USER_CAN_ACT_ON_BEHALF_OF_PROFILE])) {
  18. return false;
  19. }
  20. // only vote on Profile objects inside this voter
  21. if (!$subject instanceof Profile) {
  22. return false;
  23. }
  24. return true;
  25. }
  26. protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
  27. {
  28. $user = $token->getUser();
  29. if (!$user instanceof User) {
  30. return false;
  31. }
  32. /** @var Profile $profile */
  33. $profile = $subject;
  34. switch ($attribute) {
  35. case self::USER_CAN_VIEW_PROFILE:
  36. return $this->canView($profile, $user);
  37. case self::USER_CAN_EDIT_PROFILE:
  38. return $this->canEdit($profile, $user);
  39. case self::USER_CAN_ACT_ON_BEHALF_OF_PROFILE:
  40. return $this->canActOnBehalfOf($profile, $user);
  41. }
  42. throw new LogicException('This code should not be reached!');
  43. }
  44. private function canView(Profile $profile, User $user)
  45. {
  46. return true;
  47. }
  48. private function canEdit(Profile $profile, User $user)
  49. {
  50. return $user === $profile->getUser();
  51. }
  52. private function canActOnBehalfOf(Profile $profile, User $user)
  53. {
  54. return $user === $profile->getUser();
  55. }
  56. }