You are here

function template_preprocess_search_api_index in Search API 8

Prepares variables for search_api_index templates.

Default template: search-api-index.html.twig.

Parameters

array &$variables: An associative array containing:

  • index: The search index to display.

File

./search_api.theme.inc, line 273
Defines theme functions for the Search API module.

Code

function template_preprocess_search_api_index(array &$variables) {

  // Get the index.

  /** @var \Drupal\search_api\IndexInterface $index */
  $index = $variables['index'];
  $server = $index
    ->hasValidServer() ? $index
    ->getServerInstance() : NULL;
  $tracker = $index
    ->hasValidTracker() ? $index
    ->getTrackerInstance() : NULL;
  if ($description = $index
    ->getDescription()) {

    // Sanitize the description and append to the output.
    $variables['description'] = $description;
  }

  // Initialize the $rows variable which will hold the different parts of server
  // information.
  $rows = [];

  // Create a row template with references so we don't have to deal with the
  // complicated structure for each individual row.
  $row = [
    'data' => [
      [
        'header' => TRUE,
      ],
      '',
    ],
    'class' => [],
  ];

  // Get the individual parts of the row by reference.
  $label =& $row['data'][0]['data'];
  $info =& $row['data'][1];
  $classes =& $row['class'];

  // Check if the index is enabled.
  if ($index
    ->status()) {
    try {
      $variables['server_count'] = $index
        ->query()
        ->setProcessingLevel(QueryInterface::PROCESSING_NONE)
        ->addTag('server_index_status')
        ->range(0, 0)
        ->execute()
        ->getResultCount();
    } catch (SearchApiException $e) {
      $variables['server_count_error'] = $e
        ->getMessage();
    }
    $classes[] = 'ok';
    $info = t('enabled (<a href=":url">disable</a>)', [
      ':url' => $index
        ->toUrl('disable')
        ->toString(),
    ]);
  }
  elseif ($server && $server
    ->status()) {
    $classes[] = 'warning';
    $info = t('disabled (<a href=":url">enable</a>)', [
      ':url' => $index
        ->toUrl('enable')
        ->toString(),
    ]);
  }
  else {
    $classes[] = 'warning';
    $info = t('disabled');
  }

  // Append the row and reset variables.
  $label = t('Status');
  $classes[] = 'search-api-index-summary--status';
  $rows[] = Utility::deepCopy($row);
  $classes = [];
  foreach ($index
    ->getDatasourceIds() as $datasource_id) {

    // Check if the datasource is valid.
    if ($index
      ->isValidDatasource($datasource_id)) {
      $info = $index
        ->getDatasource($datasource_id)
        ->label();
      if ($tracker) {
        $args = [
          '@indexed' => $tracker
            ->getIndexedItemsCount($datasource_id),
          '@total' => $tracker
            ->getTotalItemsCount($datasource_id),
        ];
        $indexed = t('@indexed/@total indexed', $args);
        $args = [
          '@datasource' => $info,
          '@indexed' => $indexed,
        ];
        $info = new FormattableMarkup('@datasource <small>(@indexed)</small>', $args);
      }
    }
    else {
      $classes[] = 'error';
      $info = t('Invalid or missing datasource plugin: %datasource_id', [
        '%datasource_id' => $datasource_id,
      ]);
    }

    // Append the row and reset variables.
    $label = t('Datasource');
    $classes[] = 'search-api-index-summary--datasource';
    $rows[] = Utility::deepCopy($row);
    $classes = [];
  }

  // Check if the tracker is valid.
  if ($tracker) {
    $info = $tracker
      ->label();
  }
  else {
    $classes[] = 'error';
    $info = t('Invalid or missing tracker plugin: %tracker_id', [
      '%tracker_id' => $index
        ->getTrackerId(),
    ]);
  }

  // Append the row and reset variables.
  $label = t('Tracker');
  $classes[] = 'search-api-index-summary--tracker';
  $rows[] = Utility::deepCopy($row);
  $classes = [];

  // Check if a server is available.
  $classes[] = 'search-api-index-summary--server';
  if ($server) {
    $label = t('Server');
    $info = $server
      ->toLink(NULL, 'canonical')
      ->toString();
    $rows[] = Utility::deepCopy($row);
  }
  elseif ($index
    ->getServerId()) {
    $classes[] = 'error';
    $label = t('Server');
    $info = t('Unknown server set for index: %server_id', [
      '%server_id' => $index
        ->getServerId(),
    ]);
    $rows[] = Utility::deepCopy($row);
  }
  $classes = [];

  // Check if the index is enabled.
  if ($index
    ->status()) {
    $label = t('Server index status');
    if (isset($variables['server_count'])) {
      $vars = [
        ':url' => Url::fromUri('https://drupal.org/node/2009804#server-index-status')
          ->toString(),
      ];

      // Build the server index status info.
      $info = \Drupal::translation()
        ->formatPlural($variables['server_count'], 'There is 1 item indexed on the server for this index. (<a href=":url">More information</a>)', 'There are @count items indexed on the server for this index. (<a href=":url">More information</a>)', $vars);
    }
    else {
      $args = [
        '@message' => $variables['server_count_error'],
      ];
      $info = t('Error while checking server index status: @message', $args);
      $classes[] = 'error';
    }
    $classes[] = 'search-api-index-summary--server-index-status';
    $rows[] = Utility::deepCopy($row);
    $classes = [];
    $cron_limit = $index
      ->getOption('cron_limit', \Drupal::config('search_api.settings')
      ->get('default_cron_limit'));

    // Check if the cron limit is higher than zero.
    if ($cron_limit != 0) {
      $classes[] = 'ok';
      if ($cron_limit > 0) {
        $info = \Drupal::translation()
          ->formatPlural($cron_limit, 'During cron runs, 1 item will be indexed per batch.', 'During cron runs, @count items will be indexed per batch.');
      }
      else {
        $info = t('All items will be indexed at once during cron runs.');
      }
    }
    else {
      $classes[] = 'warning';
      $info = t('No items will be indexed during cron runs.');
    }

    // Append the row and reset variables.
    $label = t('Cron batch size');
    $classes[] = 'search-api-index-summary--cron-batch-size';
    $rows[] = Utility::deepCopy($row);
    $classes = [];

    // Add the indexing progress bar.
    if ($tracker) {
      $indexed_count = $tracker
        ->getIndexedItemsCount();
      $total_count = $tracker
        ->getTotalItemsCount();
      $variables['index_progress'] = [
        '#theme' => 'progress_bar',
        '#percent' => $total_count ? (int) (100 * $indexed_count / $total_count) : 100,
        '#message' => t('@indexed/@total indexed', [
          '@indexed' => $indexed_count,
          '@total' => $total_count,
        ]),
      ];
    }
  }

  // Append the index info table to the output.
  $variables['table'] = [
    '#theme' => 'table',
    '#rows' => $rows,
    '#attributes' => [
      'class' => [
        'search-api-index-summary',
      ],
    ],
  ];
}