src/Security/Voter/EventVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\Event;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. class EventVoter extends Voter
  10. {
  11. public function __construct(private readonly Security $security)
  12. {
  13. }
  14. protected function supports($attribute, $subject): bool
  15. {
  16. // only vote on `Event` objects
  17. if (!$subject instanceof Event) {
  18. return false;
  19. }
  20. // if the attribute isn't one we support, return false
  21. return in_array($attribute, ['edit', 'delete']);
  22. }
  23. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  24. {
  25. /**@var Event $event */
  26. $event = $subject;
  27. $user = $token->getUser();
  28. // if the user is anonymous, do not grant access
  29. if (!$user instanceof UserInterface) {
  30. return false;
  31. }
  32. // ROLE_CHIEF can do anything! The power!
  33. if ($this->security->isGranted('ROLE_CHIEF')) {
  34. return true;
  35. }
  36. return match ($attribute) {
  37. // Users may edit THEIR events
  38. 'edit' => $user === $event->getAssignedTo(),
  39. // Users may delete THEIR events
  40. 'delete' => $user === $event->getAssignedTo(),
  41. default => false,
  42. };
  43. }
  44. }