You are here

search_api_views.module in Search API 7

Integrates the Search API with Views.

File

contrib/search_api_views/search_api_views.module
View source
<?php

/**
 * @file
 * Integrates the Search API with Views.
 */

/**
 * Implements hook_views_api().
 */
function search_api_views_views_api() {
  return array(
    'api' => '3.0-alpha1',
  );
}

/**
 * Implements hook_search_api_index_insert().
 */
function search_api_views_search_api_index_insert() {

  // Make the new index available for views.
  views_invalidate_cache();
}

/**
 * Implements hook_search_api_index_update().
 */
function search_api_views_search_api_index_update(SearchApiIndex $index) {

  // Check whether index was disabled.
  $is_enabled = $index->enabled;
  $was_enabled = $index->original->enabled;
  if (!$is_enabled && $was_enabled) {
    _search_api_views_index_unavailable($index);
    return;
  }

  // Check whether the indexed fields changed.
  $old_fields = $index->original->options + array(
    'fields' => array(),
  );
  $old_fields = $old_fields['fields'];
  $new_fields = $index->options + array(
    'fields' => array(),
  );
  $new_fields = $new_fields['fields'];

  // If the index was enabled or its fields changed, invalidate the Views cache.
  if ($is_enabled != $was_enabled || $old_fields != $new_fields) {
    views_invalidate_cache();
  }
}

/**
 * Implements hook_search_api_index_delete().
 */
function search_api_views_search_api_index_delete(SearchApiIndex $index) {

  // Only do this if this is a "real" deletion, no revert.
  if (!$index
    ->hasStatus(ENTITY_IN_CODE)) {
    _search_api_views_index_unavailable($index);
  }
}

/**
 * Function for reacting to a disabled or deleted search index.
 */
function _search_api_views_index_unavailable(SearchApiIndex $index) {
  $names = array();
  $table = 'search_api_index_' . $index->machine_name;
  foreach (views_get_all_views() as $name => $view) {
    if (empty($view->disabled) && $view->base_table == $table) {
      $names[] = $name;

      // @todo: if ($index_deleted) $view->delete()?
    }
  }
  if ($names) {
    views_invalidate_cache();
    drupal_set_message(t('The following views were using the index %name: @views. You should disable or delete them.', array(
      '%name' => $index->name,
      '@views' => implode(', ', $names),
    )), 'warning');
  }
}