src/Security/Voter/RecordVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\Record;
  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 RecordVoter 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 `Record` objects
  17. if (!$subject instanceof Record) {
  18. return false;
  19. }
  20. // if the attribute isn't one we support, return false
  21. return $attribute == 'view';
  22. }
  23. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  24. {
  25. /**@var Record $record */
  26. $record = $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 view THEIR records
  38. 'view' => $user === $record->getUser(),
  39. default => false,
  40. };
  41. }
  42. }