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')) {
45 // Read in existing codes.
46 // @todo Allow to remove previously existing country codes.
47 // @see https://www.drupal.org/node/1436754
48 require_once DRUPAL_ROOT . '/core/lib/Drupal/Core/Locale/CountryManagerInterface.php';
49 require_once DRUPAL_ROOT . '/core/lib/Drupal/Core/Locale/CountryManager.php';
50 $existing_countries = CountryManager::getStandardList();
51 $countries = $existing_countries;
53 // Parse the source data into an array.
54 $data = json_decode(file_get_contents($uri));
56 foreach ($data->main->en->localeDisplayNames->territories as $code => $name) {
57 // Use any alternate codes the Drupal community wishes to.
59 // 'CI-alt-variant', // Use CI-alt-variant instead of the CI entry.
61 if (in_array($code, $alt_codes)) {
62 // Just use the first 2 character part of the alt code.
63 $code = strtok($code, '-');
66 // Skip any codes we wish to exclude from our country list.
68 // The European Union is not a country.
70 // Don't allow "Unknown Region".
73 if (in_array($code, $exclude_codes)) {
77 // Ignore every territory that doesn't have a 2 character code.
78 if (strlen($code) !== 2) {
81 $countries[(string) $code] = $name;
83 if (empty($countries)) {
84 echo 'ERROR: Did not find expected country names.' . PHP_EOL;
87 // Sort by country code (to minimize diffs).
92 foreach ($countries as $code => $name) {
93 // For .po translation file's sake, use double-quotes instead of escaped
95 $name = (strpos($name, '\'') !== FALSE ? '"' . $name . '"' : "'" . $name . "'");
96 $out .= ' ' . var_export($code, TRUE) . ' => t(' . $name . '),' . "\n";
99 // Replace the actual PHP code in standard.inc.
100 $file = DRUPAL_ROOT . '/core/lib/Drupal/Core/Locale/CountryManager.php';
101 $content = file_get_contents($file);
102 $content = preg_replace('/(\$countries = \[\n)(.+?)(^\s+\];)/ms', '$1' . $out . '$3', $content, -1, $count);
103 file_put_contents($file, $content);