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