You are here

public function SpellCheck::render in Search API Spellcheck 8

Render the area.

Parameters

bool $empty: (optional) Indicator if view result is empty or not. Defaults to FALSE.

Return value

array In any case we need a valid Drupal render array to return.

Overrides AreaPluginBase::render

File

src/Plugin/views/area/SpellCheck.php, line 125

Class

SpellCheck
Provides an area for messages.

Namespace

Drupal\search_api_spellcheck\Plugin\views\area

Code

public function render($empty = FALSE) {
  if ($this->options['search_api_spellcheck_hide_on_result'] == FALSE || $this->options['search_api_spellcheck_hide_on_result'] && $empty) {
    $cacheItem = \Drupal::cache(self::SPELLCHECK_CACHE_BIN)
      ->get($this
      ->getCacheKey());
    if ($extra_data = $cacheItem->data) {
      $filter_name = $this->options['search_api_spellcheck_filter_name'];

      // Check that we have suggestions.
      $keys = $this->view
        ->getExposedInput()[$filter_name];
      $new_data = [];
      if (!empty($extra_data['spellcheck']['suggestions'])) {

        // Loop over the suggestions and print them as links.
        foreach ($extra_data['spellcheck']['suggestions'] as $key => $value) {
          if (is_string($value)) {
            $new_data[$key] = [
              'error' => $value,
              'suggestion' => $extra_data['spellcheck']['suggestions'][$key + 1]['suggestion'][0],
            ];
          }
        }
      }
      foreach ($new_data as $datum) {
        $keys = str_replace($datum['error'], $datum['suggestion'], $keys);
      }
      $build = [
        [
          '#type' => 'html_tag',
          '#tag' => 'span',
          '#value' => $this
            ->t('Did you mean: '),
        ],
        [
          '#type' => 'link',
          '#title' => str_replace('+', ' ', $keys),
          '#url' => Url::fromRoute('<current>', [], [
            'query' => [
              'keys' => str_replace(' ', '+', $keys),
            ],
          ]),
        ],
        [
          '#type' => 'html_tag',
          '#tag' => 'span',
          '#value' => $this
            ->t('?'),
        ],
      ];
      return $build;
    }
  }
  return [];
}