function RoleAccessCheck::access

Same name in other branches
  1. 9 core/modules/user/src/Access/RoleAccessCheck.php \Drupal\user\Access\RoleAccessCheck::access()
  2. 8.9.x core/modules/user/src/Access/RoleAccessCheck.php \Drupal\user\Access\RoleAccessCheck::access()
  3. 10 core/modules/user/src/Access/RoleAccessCheck.php \Drupal\user\Access\RoleAccessCheck::access()

Checks access.

Parameters

\Symfony\Component\Routing\Route $route: The route to check against.

\Drupal\Core\Session\AccountInterface $account: The currently logged in account.

Return value

\Drupal\Core\Access\AccessResultInterface The access result.

File

core/modules/user/src/Access/RoleAccessCheck.php, line 30

Class

RoleAccessCheck
Determines access to routes based on roles.

Namespace

Drupal\user\Access

Code

public function access(Route $route, AccountInterface $account) {
    // Requirements just allow strings, so this might be a comma separated list.
    $rid_string = $route->getRequirement('_role');
    $explode_and = array_filter(array_map('trim', explode(',', $rid_string)));
    if (count($explode_and) > 1) {
        $diff = array_diff($explode_and, $account->getRoles());
        if (empty($diff)) {
            return AccessResult::allowed()->addCacheContexts([
                'user.roles',
            ]);
        }
    }
    else {
        $explode_or = array_filter(array_map('trim', explode('+', $rid_string)));
        $intersection = array_intersect($explode_or, $account->getRoles());
        if (!empty($intersection)) {
            return AccessResult::allowed()->addCacheContexts([
                'user.roles',
            ]);
        }
    }
    // If there is no allowed role, give other access checks a chance.
    return AccessResult::neutral()->addCacheContexts([
        'user.roles',
    ]);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.