You are here

public function LanguageHierarchySort::query in Language Hierarchy 2.x

Called to add the sort to a query.

Overrides SortPluginBase::query

File

src/Plugin/views/sort/LanguageHierarchySort.php, line 62

Class

LanguageHierarchySort
Provides sorting by language relevance based on language_hierarchy.

Namespace

Drupal\language_hierarchy\Plugin\views\sort

Code

public function query() {
  $this
    ->ensureMyTable();

  // Get the current language.
  $langcode = $this->languageManager
    ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
    ->getId();
  $fallback_langcodes = array_values($this->languageManager
    ->getFallbackCandidates([
    'langcode' => $langcode,
    'operation' => 'views_query',
  ]));

  // Ensure the current language is included in the fallback candidates, as
  // it doesn't necessarily have to be.
  if (!in_array($langcode, $fallback_langcodes, TRUE)) {
    $fallback_langcodes = array_merge([
      $langcode,
    ], $fallback_langcodes);
  }

  /** @var \Drupal\views\Plugin\views\query\Sql $query */
  $query = $this->query;
  $qualified_field = "{$this->tableAlias}.{$this->realField}";

  // Use case statements to sort based on list of fallback languages. Weights
  // are inverted so that descending relevance means languages later in the
  // fallback chain get sorted last.
  $case_statements = '';
  $max_weight = 0 - count($fallback_langcodes);
  foreach ($fallback_langcodes as $weight => $langcode) {
    $weight = 0 - $weight;
    $case_statements .= "WHEN {$qualified_field} = '{$langcode}' THEN {$weight} ";
  }
  $formula = "(CASE {$case_statements} ELSE {$max_weight} END)";

  // Add the field.
  $alias = $query
    ->addField(NULL, $formula, $this->tableAlias . '_language_hierarchy');
  $query
    ->addOrderBy(NULL, NULL, $this->options['order'], $alias);
}