You are here

protected function SearchApiSolrBackend::flattenKeys in Search API Solr 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/search_api/backend/SearchApiSolrBackend.php \Drupal\search_api_solr\Plugin\search_api\backend\SearchApiSolrBackend::flattenKeys()

Flatten a keys array into a single search string.

Parameters

array $keys: The keys array to flatten, formatted as specified by \Drupal\search_api\Query\QueryInterface::getKeys().

Return value

string A Solr query string representing the same keys.

1 call to SearchApiSolrBackend::flattenKeys()
SearchApiSolrBackend::search in src/Plugin/search_api/backend/SearchApiSolrBackend.php
Options on $query prefixed by 'solr_param_' will be passed natively to Solr as query parameter without the prefix. For example you can set the "Minimum Should Match" parameter 'mm' to '75%' like this:

File

src/Plugin/search_api/backend/SearchApiSolrBackend.php, line 2345

Class

SearchApiSolrBackend
Apache Solr backend for search api.

Namespace

Drupal\search_api_solr\Plugin\search_api\backend

Code

protected function flattenKeys(array $keys) {
  $k = [];
  $pre = '+';
  if (isset($keys['#conjunction']) && $keys['#conjunction'] == 'OR') {
    $pre = '';
  }
  $neg = empty($keys['#negation']) ? '' : '-';
  foreach ($keys as $key_nr => $key) {

    // We cannot use \Drupal\Core\Render\Element::children() anymore because
    // $keys is not a valid render array.
    if (is_string($key_nr) && $key_nr[0] === '#' || !$key) {
      continue;
    }
    if (is_array($key)) {
      $subkeys = $this
        ->flattenKeys($key);
      if ($subkeys) {
        $nested_expressions = TRUE;
        $k[] = "({$subkeys})";
      }
    }
    else {
      $k[] = $this
        ->getSolrConnector()
        ->getQueryHelper()
        ->escapePhrase(trim($key));
    }
  }
  if (!$k) {
    return '';
  }

  // Formatting the keys into a Solr query can be a bit complex. Keep in mind
  // that the default operator is OR. The following code will produce filters
  // that look like this:
  //
  // #conjunction | #negation | return value
  // ----------------------------------------------------------------
  // AND          | FALSE     | (+A +B +C)
  // AND          | TRUE      | -(+A +B +C)
  // OR           | FALSE     | (A B C)
  // OR           | TRUE      | -(A B C)
  //
  // If there was just a single, unnested key, we can ignore all this.
  if (count($k) == 1 && empty($nested_expressions)) {
    return $neg . reset($k);
  }
  return $neg . '(' . $pre . implode(' ' . $pre, $k) . ')';
}