You are here

function pbf_node_grants in Permissions by field 8

Implements hook_node_grants().

File

./pbf.module, line 41
Contains pbf.module.

Code

function pbf_node_grants(AccountInterface $account, $op) {

  // First grant a grant to the author for own content.
  $grants['pbf_author'] = [
    $account
      ->id(),
  ];

  // Grant to the user referenced by a Pbf field.
  $grants['pbf_' . PBF_BY_USER_ID] = [
    $account
      ->id(),
  ];

  // Grant to the user according roles.
  $roles = $account
    ->getRoles();
  $role_ids = \Drupal::config('pbf.settings')
    ->get('pbf_roles_gids');
  foreach ($roles as $role) {
    $grants['pbf_' . PBF_BY_ROLE_ID][] = $role_ids[$role];
  }

  // Grant to the user according to his Pbf field referencing node or term.
  $user = User::load($account
    ->id());
  $field_definitions = $user
    ->getFieldDefinitions();
  foreach ($field_definitions as $field_name => $field_definition) {
    if ($field_definition instanceof FieldConfigInterface && $field_definition
      ->getType() == 'pbf') {
      $values = $user->{$field_name}
        ->getValue();
      if (empty($values)) {
        continue;
      }
      $target_entity_type_id = $field_definition
        ->getSetting('target_type');
      switch ($target_entity_type_id) {
        case 'node':
        case 'taxonomy_term':
          foreach ($values as $value) {

            // On user edit account page, if the cardinality of Pbf field is
            // unlimited, we can have an empty array for $value which
            // correspond to the empty input field on the form edit.
            if ($value) {
              $grants['pbf_' . $field_name][] = $value['target_id'];
            }
          }
          break;
        case 'user':
          foreach ($values as $value) {

            // On user edit account page, if the cardinality of Pbf field is
            // unlimited, we can have an empty array for $value which
            // correspond to the empty input field on the form edit.
            if ($value) {
              $grants['pbf_' . $field_name][] = $value['target_id'];
            }
          }
          break;
      }
    }
  }
  return $grants;
}