src/Security/Voter/ClientPermissionVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. class ClientPermissionVoter extends Voter
  7. {
  8. const ATTR = 'clientPermission';
  9. protected function supports(string $attribute, $subject): bool
  10. {
  11. // if the attribute isn't one we support, return false
  12. if ($attribute !== self::ATTR) {
  13. return false;
  14. }
  15. // only vote on `Invoice` objects
  16. if (!is_string($subject)) {
  17. return false;
  18. }
  19. return true;
  20. }
  21. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  22. {
  23. $loggedUser = $token->getUser();
  24. if (!$loggedUser instanceof User) {
  25. // the user must be logged in; if not, deny access
  26. return false;
  27. }
  28. /** @var string $permissionName */
  29. $permissionName = $subject;
  30. foreach ($loggedUser->getClient()->getPermissions() as $permission) {
  31. if ($permission->getName() === $permissionName) {
  32. return true;
  33. }
  34. }
  35. return false;
  36. }
  37. }