annotate core/modules/user/src/Access/RoleAccessCheck.php @ 19:fa3358dc1485 tip

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