LanguageHierarchySort.php in Language Hierarchy 2.x
File
src/Plugin/views/sort/LanguageHierarchySort.php
View source
<?php
namespace Drupal\language_hierarchy\Plugin\views\sort;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\views\Plugin\views\sort\SortPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LanguageHierarchySort extends SortPluginBase {
protected $languageManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->languageManager = $language_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('language_manager'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['order'] = [
'default' => 'DESC',
];
return $options;
}
public function query() {
$this
->ensureMyTable();
$langcode = $this->languageManager
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
$fallback_langcodes = array_values($this->languageManager
->getFallbackCandidates([
'langcode' => $langcode,
'operation' => 'views_query',
]));
if (!in_array($langcode, $fallback_langcodes, TRUE)) {
$fallback_langcodes = array_merge([
$langcode,
], $fallback_langcodes);
}
$query = $this->query;
$qualified_field = "{$this->tableAlias}.{$this->realField}";
$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)";
$alias = $query
->addField(NULL, $formula, $this->tableAlias . '_language_hierarchy');
$query
->addOrderBy(NULL, NULL, $this->options['order'], $alias);
}
}