You are here

function domain_entity_entity_access in Domain Access Entity 8

Implements hook_entity_access().

See also

domain_access_node_access

File

./domain_entity.module, line 438
Enables domain access for entities, and access query alter.

Code

function domain_entity_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {

  // Ensure quick administration.
  $user = User::load($account
    ->id());
  $is_admin = \Drupal::service('router.admin_context')
    ->isAdminRoute();
  if ($is_admin && $user
    ->hasRole("administrator")) {
    return AccessResult::neutral();
  }

  // Should be a fieldable entity with domain field.
  if (!$entity instanceof FieldableEntityInterface) {
    return AccessResult::neutral();
  }
  if (!$entity
    ->hasField(DomainEntityMapper::FIELD_NAME)) {
    return AccessResult::neutral();
  }

  // Restrict access like it's done in domain_access module.
  $type = $entity
    ->bundle();
  $typeEntity = $entity
    ->getEntityTypeId();
  $manager = \Drupal::service('domain_access.manager');
  if ($operation == 'view' && $manager
    ->checkEntityAccess($entity, $account)) {
    if (method_exists($entity, "isPublished") && $entity
      ->isPublished()) {
      return AccessResult::neutral();
    }
    elseif ($account
      ->hasPermission('view unpublished domain content')) {
      return AccessResult::neutral();
    }
  }
  if ($operation == 'update') {
    if ($account
      ->hasPermission('update ' . $type . ' ' . $typeEntity . ' content on assigned domains') && $manager
      ->checkEntityAccess($entity, $account)) {
      return AccessResult::neutral();
    }
    elseif ($account
      ->hasPermission('edit domain content') && $manager
      ->checkEntityAccess($entity, $account)) {
      return AccessResult::neutral();
    }
  }
  if ($operation == 'delete') {
    if ($account
      ->hasPermission('delete ' . $type . ' ' . $typeEntity . ' content on assigned domains') && $manager
      ->checkEntityAccess($entity, $account)) {
      return AccessResult::neutral();
    }
    elseif ($account
      ->hasPermission('delete domain content') && $manager
      ->checkEntityAccess($entity, $account)) {
      return AccessResult::neutral();
    }
  }
  $domains = _domain_entity_get_related_domains($entity);

  // If specific domains was not selected means:
  // Should be accessible for all domains (no restrictions).
  if (!$domains) {
    return AccessResult::neutral();
  }
  $current_domain = domain_entity_get_domain();
  if (isset($domains[$current_domain
    ->id()])) {
    return AccessResult::neutral();
  }
  return AccessResult::forbidden()
    ->addCacheableDependency($current_domain);
}