summaryrefslogtreecommitdiff
blob: 65954f0f6c02be3d74e3f9d29921e0700bb4b735 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

use MediaWiki\MediaWikiServices;

/**
 * A class for querying translated country names from CLDR data.
 *
 * @author Niklas Laxström
 * @author Ryan Kaldari
 * @copyright Copyright © 2007-2011
 * @license GPL-2.0-or-later
 */
class CountryNames extends CldrNames {

	private static $cache = [];

	/**
	 * Get localized country names for a particular language, using fallback languages for missing
	 * items.
	 *
	 * @param string $code The language to return the list in
	 * @return array an associative array of country codes and localized country names
	 */
	public static function getNames( $code ) {
		// Load country names localized for the requested language
		$names = self::loadLanguage( $code );

		// Load missing country names from fallback languages
		$fallbacks = MediaWikiServices::getInstance()->getLanguageFallback()->getAll( $code );
		foreach ( $fallbacks as $fallback ) {
			// Overwrite the things in fallback with what we have already
			$names = array_merge( self::loadLanguage( $fallback ), $names );
		}

		return $names;
	}

	/**
	 * Load country names localized for a particular language. Helper function for getNames.
	 *
	 * @param string $code The language to return the list in
	 * @return array an associative array of country codes and localized country names
	 */
	private static function loadLanguage( $code ) {
		if ( !isset( self::$cache[$code] ) ) {

			$langNameUtils = MediaWikiServices::getInstance()->getLanguageNameUtils();

			/* Load override for wrong or missing entries in cldr */
			$override = __DIR__ . '/../LocalNames/' . self::getOverrideFileName( $code );
			if ( $langNameUtils->isValidBuiltInCode( $code ) && file_exists( $override ) ) {
				$countryNames = false;
				require $override;
				// @phan-suppress-next-line PhanImpossibleCondition
				if ( is_array( $countryNames ) ) {
					self::$cache[$code] = $countryNames;
				}
			}

			$filename = __DIR__ . '/../CldrNames/' . self::getFileName( $code );
			if ( $langNameUtils->isValidBuiltInCode( $code ) && file_exists( $filename ) ) {
				$countryNames = false;
				require $filename;
				// @phan-suppress-next-line PhanImpossibleCondition
				if ( is_array( $countryNames ) ) {
					if ( isset( self::$cache[$code] ) ) {
						// Add to existing list of localized country names
						self::$cache[$code] += $countryNames;
					} else {
						// No list exists, so create it
						self::$cache[$code] = $countryNames;
					}
				}
			} else {
				wfDebug( __METHOD__ . ": Unable to load country names for $filename\n" );
			}
		}

		return self::$cache[$code] ?? [];
	}
}