You are here

function language_hierarchy_update_priorities in Language Hierarchy 8

Same name and namespace in other branches
  1. 2.x language_hierarchy.module \language_hierarchy_update_priorities()

Updates the language_hierarchy_priority table based on current configuration.

6 calls to language_hierarchy_update_priorities()
LanguageHierarchyConfigEventSubscriber::onConfigImport in src/EventSubscriber/LanguageHierarchyConfigEventSubscriber.php
This method is called when the config.importer.import event is dispatched.
language_hierarchy_configurable_language_delete in ./language_hierarchy.module
Implements hook_ENTITY_TYPE_delete().
language_hierarchy_configurable_language_insert in ./language_hierarchy.module
Implements hook_ENTITY_TYPE_insert().
language_hierarchy_configurable_language_update in ./language_hierarchy.module
Implements hook_ENTITY_TYPE_update().
language_hierarchy_install in ./language_hierarchy.install
Implements hook_install().

... See full list

File

./language_hierarchy.module, line 303
Add sublanguage handling functionality to Drupal.

Code

function language_hierarchy_update_priorities() {
  $langcode_priorities = [];
  $manager = Drupal::languageManager();
  $languages = $manager
    ->getLanguages();

  // Start with ordering by weight. We frame these in the negative numbers so
  // that any (later-discovered) ordering-by-hierarchy immediately trumps it.
  uasort($languages, function ($a, $b) {
    return $a
      ->getWeight() < $b
      ->getWeight() ? -1 : 1;
  });
  foreach (array_values($languages) as $position_wrt_weight => $language) {
    $langcode_priorities[$language
      ->getId()] = -$position_wrt_weight - 1;
  }

  // Set each langcode's priority to its depth in its hierarchy.
  foreach ($languages as $language) {
    $langcode = $language
      ->getId();
    $context = [
      'langcode' => $langcode,
      'operation' => 'language_hierarchy_update_priorities',
    ];
    $candidates = $manager
      ->getFallbackCandidates($context);
    $candidates = array_filter($candidates, function ($a) use ($langcode) {
      return !in_array($a, [
        LanguageInterface::LANGCODE_NOT_SPECIFIED,
        $langcode,
      ]);
    });
    if (!empty($candidates)) {
      $langcode_priorities[$langcode] = count($candidates);
    }
  }
  $database = Drupal::database();
  $transaction = $database
    ->startTransaction();
  $database
    ->truncate('language_hierarchy_priority')
    ->execute();
  $query = $database
    ->insert('language_hierarchy_priority')
    ->fields([
    'langcode',
    'priority',
  ]);
  foreach ($langcode_priorities as $langcode => $priority) {
    $query
      ->values([
      'langcode' => $langcode,
      'priority' => $priority,
    ]);
  }
  $query
    ->execute();
}