RoleAccessCheck.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Drupal\user\Access;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Routing\Access\AccessInterface;
  5. use Drupal\Core\Session\AccountInterface;
  6. use Symfony\Component\Routing\Route;
  7. /**
  8. * Determines access to routes based on roles.
  9. *
  10. * You can specify the '_role' key on route requirements. If you specify a
  11. * single role, users with that role with have access. If you specify multiple
  12. * ones you can conjunct them with AND by using a "," and with OR by using "+".
  13. */
  14. class RoleAccessCheck implements AccessInterface {
  15. /**
  16. * Checks access.
  17. *
  18. * @param \Symfony\Component\Routing\Route $route
  19. * The route to check against.
  20. * @param \Drupal\Core\Session\AccountInterface $account
  21. * The currently logged in account.
  22. *
  23. * @return \Drupal\Core\Access\AccessResultInterface
  24. * The access result.
  25. */
  26. public function access(Route $route, AccountInterface $account) {
  27. // Requirements just allow strings, so this might be a comma separated list.
  28. $rid_string = $route->getRequirement('_role');
  29. $explode_and = array_filter(array_map('trim', explode(',', $rid_string)));
  30. if (count($explode_and) > 1) {
  31. $diff = array_diff($explode_and, $account->getRoles());
  32. if (empty($diff)) {
  33. return AccessResult::allowed()->addCacheContexts(['user.roles']);
  34. }
  35. }
  36. else {
  37. $explode_or = array_filter(array_map('trim', explode('+', $rid_string)));
  38. $intersection = array_intersect($explode_or, $account->getRoles());
  39. if (!empty($intersection)) {
  40. return AccessResult::allowed()->addCacheContexts(['user.roles']);
  41. }
  42. }
  43. // If there is no allowed role, give other access checks a chance.
  44. return AccessResult::neutral()->addCacheContexts(['user.roles']);
  45. }
  46. }