src/Security/Voter/EventVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Event;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class EventVoter extends Voter
  9. {
  10. const EVENT_MANAGE = 'EVENT_MANAGE';
  11. /**
  12. * @var Security
  13. */
  14. private $security;
  15. /**
  16. * UserVoter constructor.
  17. * @param Security $security
  18. */
  19. public function __construct(Security $security)
  20. {
  21. $this->security = $security;
  22. }
  23. protected function supports($attribute, $subject)
  24. {
  25. return in_array($attribute, [self::EVENT_MANAGE])
  26. && $subject instanceof Event;
  27. }
  28. protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
  29. {
  30. /** @var User $user */
  31. $user = $token->getUser();
  32. // if the user is anonymous, do not grant access
  33. if (!$user instanceof User) {
  34. return false;
  35. }
  36. // if the user is anonymous, do not grant access
  37. if (!in_array('ROLE_ADMIN', $user->getRoles()) || !in_array('ROLE_ECITY', $user->getRoles())) {
  38. return false;
  39. }
  40. // get user permissions
  41. $permissions = $user->getPermissions();
  42. if( !is_array($permissions) ) {
  43. return false;
  44. }
  45. switch ($attribute) {
  46. case self::EVENT_MANAGE:
  47. if (in_array('EVENT_MANAGE', $permissions)) {
  48. return true;
  49. }
  50. break;
  51. }
  52. return false;
  53. }
  54. }