You are here

public function GroupCheck::access in Organic groups 8

Checks if the user has group related permissions.

If the route parameter names don't have {entity_type_id} or {entity_id} you can still use this access check, by passing the "entity_type_id" definition using the Route::setOption method. see \Drupal\og\Routing\RouteSubscriber::alterRoutes as an example.

Parameters

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

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

\Drupal\Core\Routing\RouteMatchInterface $route_match: The rout match object.

string $entity_type_id: (optional) The entity type ID.

string $entity_id: The entity ID. If the ID is not sent, the access method will try to extract it from the route matcher.

Return value

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

File

src/Access/GroupCheck.php, line 74

Class

GroupCheck
Determines access to routes based on group permissions for the current user.

Namespace

Drupal\og\Access

Code

public function access(AccountInterface $user, Route $route, RouteMatchInterface $route_match, $entity_type_id = NULL, $entity_id = NULL) {
  $group = NULL;
  if (!$entity_type_id) {
    $parameter_name = $route_match
      ->getRouteObject()
      ->getOption('_og_entity_type_id');
    if (!$parameter_name) {
      throw new \BadMethodCallException('Group definition is missing from the router. Did you define $route->setOption(\'_og_entity_type_id\', $entity_type_id) in your route declaration?');
    }

    /** @var \Drupal\Core\Entity\EntityInterface $group */
    if (!($group = $route_match
      ->getParameter($parameter_name))) {
      return AccessResult::forbidden();
    }
    $entity_type_id = $group
      ->getEntityTypeId();
  }

  // No access if the entity type doesn't exist.
  if (!$this->entityTypeManager
    ->getDefinition($entity_type_id, FALSE)) {
    return AccessResult::forbidden();
  }
  $entity_storage = $this->entityTypeManager
    ->getStorage($entity_type_id);
  $group = $group ?: $entity_storage
    ->load($entity_id);

  // No access if no entity was loaded or it's not a group.
  if (!$group || !Og::isGroup($entity_type_id, $group
    ->bundle())) {
    return AccessResult::forbidden();
  }

  // Iterate over the permissions.
  foreach (explode('|', $route
    ->getRequirement('_og_user_access_group')) as $permission) {
    if ($this->ogAccess
      ->userAccess($group, $permission, $user)
      ->isAllowed()) {
      return AccessResult::allowed();
    }
  }
  return AccessResult::forbidden();
}