function Language::sort

Same name in other branches
  1. 9 core/lib/Drupal/Core/Language/Language.php \Drupal\Core\Language\Language::sort()
  2. 10 core/lib/Drupal/Core/Language/Language.php \Drupal\Core\Language\Language::sort()
  3. 11.x core/lib/Drupal/Core/Language/Language.php \Drupal\Core\Language\Language::sort()

Sort language objects.

Parameters

\Drupal\Core\Language\LanguageInterface[] $languages: The array of language objects keyed by langcode.

3 calls to Language::sort()
ConfigurableLanguageManager::getLanguages in core/modules/language/src/ConfigurableLanguageManager.php
Returns a list of languages set up on the site.
ConfigurableLanguageManager::getNativeLanguages in core/modules/language/src/ConfigurableLanguageManager.php
Returns a list of languages set up on the site in their native form.
LanguageUnitTest::testSortArrayOfLanguages in core/tests/Drupal/Tests/Core/Language/LanguageUnitTest.php
Tests sorting an array of language objects.

File

core/lib/Drupal/Core/Language/Language.php, line 146

Class

Language
An object containing the information for an interface language.

Namespace

Drupal\Core\Language

Code

public static function sort(&$languages) {
    uasort($languages, function (LanguageInterface $a, LanguageInterface $b) {
        $a_weight = $a->getWeight();
        $b_weight = $b->getWeight();
        if ($a_weight == $b_weight) {
            $a_name = $a->getName();
            $b_name = $b->getName();
            // If either name is a TranslatableMarkup object it can not be converted
            // to a string. This is because translation requires a sorted list of
            // languages thereby causing an infinite loop. Determine the order based
            // on ID if this is the case.
            if ($a_name instanceof TranslatableMarkup || $b_name instanceof TranslatableMarkup) {
                $a_name = $a->getId();
                $b_name = $b->getId();
            }
            return strnatcasecmp($a_name, $b_name);
        }
        return $a_weight < $b_weight ? -1 : 1;
    });
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.