6 * Updates CLDR codes in CountryManager.php to latest data.
8 * We rely on the CLDR data set, because it is easily accessible, scriptable,
9 * and in the right human-readable format.
12 use Drupal\Core\Locale\CountryManager;
14 // Determine DRUPAL_ROOT.
15 $dir = dirname(__FILE__);
16 while (!defined('DRUPAL_ROOT')) {
17 if (is_dir($dir . '/core')) {
18 define('DRUPAL_ROOT', $dir);
23 // Determine source data file URI to process.
24 $uri = DRUPAL_ROOT . '/territories.json';
26 if (!file_exists($uri)) {
28 - Choose the latest release data from http://cldr.unicode.org/index/downloads
29 and download the json.zip file.
30 - Unzip the json.zip file and place the main/en/territories.json in the
31 Drupal root directory.
34 exit('CLDR data file not found. (' . $uri . ")\n\n" . $usage . "\n");
37 // Fake the t() function used in CountryManager.php instead of attempting a full
38 // Drupal bootstrap of core/includes/bootstrap.inc (where t() is declared).
39 if (!function_exists('t')) {
47 // Read in existing codes.
48 // @todo Allow to remove previously existing country codes.
49 // @see https://www.drupal.org/node/1436754
50 require_once DRUPAL_ROOT . '/core/lib/Drupal/Core/Locale/CountryManagerInterface.php';
51 require_once DRUPAL_ROOT . '/core/lib/Drupal/Core/Locale/CountryManager.php';
52 $existing_countries = CountryManager::getStandardList();
53 $countries = $existing_countries;
55 // Parse the source data into an array.
56 $data = json_decode(file_get_contents($uri));
58 foreach ($data->main->en->localeDisplayNames->territories as $code => $name) {
59 // Use any alternate codes the Drupal community wishes to.
61 // 'CI-alt-variant', // Use CI-alt-variant instead of the CI entry.
63 if (in_array($code, $alt_codes)) {
64 // Just use the first 2 character part of the alt code.
65 $code = strtok($code, '-');
68 // Skip any codes we wish to exclude from our country list.
70 // The European Union is not a country.
72 // Don't allow "Unknown Region".
75 if (in_array($code, $exclude_codes)) {
79 // Ignore every territory that doesn't have a 2 character code.
80 if (strlen($code) !== 2) {
83 $countries[(string) $code] = $name;
85 if (empty($countries)) {
86 echo 'ERROR: Did not find expected country names.' . PHP_EOL;
89 // Sort by country code (to minimize diffs).
94 foreach ($countries as $code => $name) {
95 // For .po translation file's sake, use double-quotes instead of escaped
97 $name = (strpos($name, '\'') !== FALSE ? '"' . $name . '"' : "'" . $name . "'");
98 $out .= ' ' . var_export($code, TRUE) . ' => t(' . $name . '),' . "\n";
101 // Replace the actual PHP code in standard.inc.
102 $file = DRUPAL_ROOT . '/core/lib/Drupal/Core/Locale/CountryManager.php';
103 $content = file_get_contents($file);
104 $content = preg_replace('/(\$countries = \[\n)(.+?)(^\s+\];)/ms', '$1' . $out . '$3', $content, -1, $count);
105 file_put_contents($file, $content);