You are here

search_api_test_views.module in Search API 8

Contains hook implementations for the Search API Views Test module.

File

tests/search_api_test_views/search_api_test_views.module
View source
<?php

/**
 * @file
 * Contains hook implementations for the Search API Views Test module.
 */
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\search_api\Query\QueryInterface;

/**
 * Implements hook_search_api_query_alter().
 *
 * - Prints the contents of the "search_api_retrieved_field_values" query option
 *   to the page (if present) so it can be checked by the testing code.
 * - Optionally alters the query to include custom cacheability metadata, so
 *   that we can test if modules can alter the cacheability of search queries.
 */
function search_api_test_views_search_api_query_alter(QueryInterface $query) {
  $fields = $query
    ->getOption('search_api_retrieved_field_values');
  if ($fields) {
    \Drupal::messenger()
      ->addStatus("'" . implode("' '", $fields) . "'");
  }
  $alter_cache_metadata = \Drupal::state()
    ->get('search_api_test_views.alter_query_cacheability_metadata', FALSE);
  if ($alter_cache_metadata && $query instanceof RefinableCacheableDependencyInterface) {

    // Alter in some imaginary cacheability metadata for testing.
    $query
      ->addCacheContexts([
      'search_api_test_context',
    ]);
    $query
      ->addCacheTags([
      'search_api:test_tag',
    ]);
    $query
      ->mergeCacheMaxAge(100);
  }
}

/**
 * Implements hook_entity_type_alter().
 */
function search_api_test_views_entity_type_alter(array &$entity_types) {

  // We need list builder for entity type in order to test operations column.
  if (!empty($entity_types['entity_test_mulrev_changed'])) {
    $entity_types['entity_test_mulrev_changed']
      ->setListBuilderClass(EntityListBuilder::class);
  }
}

/**
 * Implements hook_entity_operation().
 */
function search_api_test_views_entity_operation(EntityInterface $entity) {
  if ($entity
    ->getEntityTypeId() !== 'entity_test_mulrev_changed') {
    return [];
  }

  // For testing purpose we want to have one entity without operations.
  if ($entity
    ->id() == 2) {
    return [];
  }
  $operations['edit'] = [
    'title' => t('Edit'),
    'url' => $entity
      ->toUrl('edit-form'),
    'weight' => 0,
  ];
  $operations['delete'] = [
    'title' => t('Delete'),
    'url' => $entity
      ->toUrl('delete-form'),
    'weight' => 1,
  ];
  return $operations;
}