You are here

function search_api_node_access_records_alter in Search API 8

Same name and namespace in other branches
  1. 7 search_api.module \search_api_node_access_records_alter()

Implements hook_node_access_records_alter().

Marks the node and its comments changed for indexes that use the "Content access" processor.

File

./search_api.module, line 264
Provides a rich framework for creating searches.

Code

function search_api_node_access_records_alter(array &$grants, NodeInterface $node) {

  /** @var \Drupal\search_api\IndexInterface $index */
  foreach (Index::loadMultiple() as $index) {
    if (!$index
      ->hasValidTracker() || !$index
      ->status()) {
      continue;
    }
    if (!$index
      ->isValidProcessor('content_access')) {
      continue;
    }
    foreach ($index
      ->getDatasources() as $datasource_id => $datasource) {
      switch ($datasource
        ->getEntityTypeId()) {
        case 'node':

          // Don't index the node if search_api_skip_tracking is set on it.
          if ($node->search_api_skip_tracking) {
            continue 2;
          }
          $item_id = $datasource
            ->getItemId($node
            ->getTypedData());
          if ($item_id !== NULL) {
            $index
              ->trackItemsUpdated($datasource_id, [
              $item_id,
            ]);
          }
          break;
        case 'comment':
          if (!isset($comments)) {
            $comment_ids = \Drupal::entityQuery('comment')
              ->accessCheck(FALSE)
              ->condition('entity_id', (int) $node
              ->id())
              ->condition('entity_type', 'node')
              ->execute();

            /** @var \Drupal\comment\CommentInterface[] $comments */
            $comments = Comment::loadMultiple($comment_ids);
          }
          $item_ids = [];
          foreach ($comments as $comment) {
            $item_id = $datasource
              ->getItemId($comment
              ->getTypedData());
            if ($item_id !== NULL) {
              $item_ids[] = $item_id;
            }
          }
          if ($item_ids) {
            $index
              ->trackItemsUpdated($datasource_id, $item_ids);
          }
          break;
      }
    }
  }
}