You are here

function search_api_exclude_search_api_index_items_alter in Search API exclude 7

Implements hook_search_api_index_items_alter().

File

./search_api_exclude.module, line 23
Allows users to exclude specific nodes from indexing by Search API.

Code

function search_api_exclude_search_api_index_items_alter(array &$items, SearchApiIndex $index) {

  // TODO: Simplify this code when https://www.drupal.org/node/2666036 is
  // committed and in a stable release.
  $index_is_multi_entity = $index
    ->datasource() instanceof SearchApiCombinedEntityDataSourceController;
  if ($index_is_multi_entity) {
    $index_uses_nodes = in_array('node', $index->options['datasource']['types']);
  }
  else {
    $index_uses_nodes = $index
      ->getEntityType() === 'node';
  }
  if ($index_uses_nodes) {
    $nids_to_ids = array();

    // Item IDs might not be identical with node NIDs, and there might be
    // multiple search items (with different item IDs) mapped to the same node.
    // (E.g., with the Search API Entity Translation module.)
    foreach ($items as $item_id => $item) {
      if ($index_is_multi_entity) {
        if ($item->item_type == 'node' && isset($item->node->nid)) {
          $nids_to_ids[$item->node->nid][] = $item_id;
        }
      }
      else {
        if (isset($item->nid)) {
          $nids_to_ids[$item->nid][] = $item_id;
        }
      }
    }
    foreach (search_api_exclude_get_excluded(array_keys($nids_to_ids)) as $nid) {
      foreach ($nids_to_ids[$nid] as $item_id) {
        unset($items[$item_id]);
      }
    }
  }
}