You are here

function domain_access_entity_field_access in Domain Access 8

Implements hook_entity_field_access().

Hides the domain access fields from the entity add/edit forms when the user cannot access them.

File

domain_access/domain_access.module, line 440
Domain-based access control for content.

Code

function domain_access_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {

  // If not editing an entity, do nothing.
  if ($operation !== 'edit' || empty($items)) {
    return AccessResult::neutral();
  }

  // The entity the field is attached to.
  $entity = $items
    ->getEntity();
  if ($field_definition
    ->getName() == DomainAccessManagerInterface::DOMAIN_ACCESS_FIELD) {
    if ($entity instanceof AccountInterface) {
      $access = AccessResult::allowedIfHasPermissions($account, [
        'assign domain editors',
        'assign editors to any domain',
      ], 'OR');
    }
    elseif ($entity instanceof NodeInterface) {

      // Treat any other entity as content.
      $access = AccessResult::allowedIfHasPermissions($account, [
        'publish to any domain',
        'publish to any assigned domain',
      ], 'OR');
    }

    // allowedIfHasPermissions returns allowed() or neutral().
    // In this case, we want it to be forbidden,
    // if user doesn't have the permissions above.
    if (isset($access) && !$access
      ->isAllowed()) {
      return AccessResult::forbidden();
    }
  }
  elseif ($field_definition
    ->getName() == DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD) {
    if ($entity instanceof AccountInterface) {
      return AccessResult::forbiddenIf(!$account
        ->hasPermission('assign editors to any domain'));
    }
    elseif ($entity instanceof NodeInterface) {

      // Treat any other entity as content.
      return AccessResult::forbiddenIf(!$account
        ->hasPermission('publish to any domain'));
    }
  }
  return AccessResult::neutral();
}