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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
<?php
namespace Punic;
/**
* Territory-related stuff.
*/
class Territory
{
/**
* Retrieve the name of a territory (country, continent, ...).
*
* @param string $territoryCode The territory code
* @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
*
* @return string Returns the localized territory name (returns $territoryCode if not found)
*/
public static function getName($territoryCode, $locale = '')
{
$result = $territoryCode;
if (preg_match('/^[a-z0-9]{2,3}$/i', $territoryCode)) {
$territoryCode = strtoupper($territoryCode);
$data = Data::get('territories', $locale);
if (isset($data[$territoryCode])) {
$result = $data[$territoryCode];
}
}
return $result;
}
/**
* Return the list of continents in the form of an array with key=ID, value=name.
*
* @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
*
* @return array
*/
public static function getContinents($locale = '')
{
return static::getList('C', $locale);
}
/**
* Return the list of countries in the form of an array with key=ID, value=name.
*
* @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
*
* @return array
*/
public static function getCountries($locale = '')
{
return static::getList('c', $locale);
}
/**
* Return a list of continents and relative countries. The resulting array is in the following form (JSON representation):
* ```json
* {
* "002": {
* "name": "Africa",
* "children": {
* "DZ": {"name": "Algeria"},
* "AO": {"name": "Angola"},
* ...
* }
* },
* "150": {
* "name": "Europe",
* "children": {
* "AL": {"name": "Albania"},
* "AD": {"name": "Andorra"},
* ...
* }
* }
* ...
* }
* ```
* The arrays are sorted by territory name.
*
* @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
*
* @return array
*/
public static function getContinentsAndCountries($locale = '')
{
return static::getList('Cc', $locale);
}
/**
* Return a list of some specified territory, structured or not.
* $levels control which data you want to retrieve. It can be one or more of the following values:
* <ul>
* <li>'W': world</li>
* <li>'C': continents</li>
* <li>'S': sub-continents</li>
* <li>'c': countries</li>
* </ul>
* If only one level is specified you'll get a flat list (like the one returned by {@link getContinents}).
* If one or more levels are specified, you'll get a structured list (like the one returned by {@link getContinentsAndCountries}).
*
* @param string $levels A string with one or more of the characters: 'W' (for world), 'C' (for continents), 'S' (for sub-continents), 'c' (for countries)
* @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
*
* @throws Exception\BadArgumentType
*
* @return array
*
* @see http://www.unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html
*/
public static function getList($levels = 'W', $locale = '')
{
static $levelMap = array('W' => 0, 'C' => 1, 'S' => 2, 'c' => 3);
$decodedLevels = array();
$n = is_string($levels) ? strlen($levels) : 0;
if ($n > 0) {
for ($i = 0; $i < $n; ++$i) {
$l = substr($levels, $i, 1);
if (!isset($levelMap[$l])) {
$decodedLevels = array();
break;
}
if (!in_array($levelMap[$l], $decodedLevels, true)) {
$decodedLevels[] = $levelMap[$l];
}
}
}
if (count($decodedLevels) === 0) {
throw new \Punic\Exception\BadArgumentType($levels, "list of territory kinds: it should be a list of one or more of the codes '".implode("', '", array_keys($levelMap))."'");
}
$struct = self::filterStructure(self::getStructure(), $decodedLevels, 0);
$flatList = (count($decodedLevels) > 1) ? false : true;
$finalized = self::finalizeWithNames(Data::get('territories', $locale), $struct, $flatList);
if ($flatList) {
$sorter = new \Punic\Comparer();
$sorter->sort($finalized, true);
} else {
$finalized = static::sort($finalized);
}
return $finalized;
}
/**
* Return a list of territory identifiers for which we have some info (languages, population, literacy level, Gross Domestic Product).
*
* @return array The list of territory IDs for which we have some info
*/
public static function getTerritoriesWithInfo()
{
return array_keys(Data::getGeneric('territoryInfo'));
}
/**
* Return the list of languages spoken in a territory.
*
* @param string $territoryCode The territory code
* @param string $filterStatuses Filter language status.
* <ul>
* <li>If empty no filter will be applied</li>
* <li>'o' to include official languages</li>
* <li>'r' to include official regional languages</li>
* <li>'f' to include de facto official languages</li>
* <li>'m' to include official minority languages</li>
* <li>'u' to include unofficial or unknown languages</li>
* </ul>
* @param string $onlyCodes Set to true to retrieve only the language codes. If set to false (default) you'll receive a list of arrays with these keys:
* <ul>
* <li>string id: the language identifier</li>
* <li>string status: 'o' for official; 'r' for official regional; 'f' for de facto official; 'm' for official minority; 'u' for unofficial or unknown</li>
* <li>number population: the amount of people speaking the language (%)</li>
* <li>number|null writing: the amount of people able to write (%). May be null if no data is available</li>
* </ul>
*
* @return array|null Return the languages spoken in the specified territory, as described by the $onlyCodes parameter (or null if $territoryCode is not valid or no data is available)
*/
public static function getLanguages($territoryCode, $filterStatuses = '', $onlyCodes = false)
{
$result = null;
$info = self::getTerritoryInfo($territoryCode);
if (is_array($info)) {
$result = array();
foreach ($info['languages'] as $languageID => $languageInfo) {
if (!isset($languageInfo['status'])) {
$languageInfo['status'] = 'u';
}
if ((strlen($filterStatuses) === 0) || (stripos($filterStatuses, $languageInfo['status']) !== false)) {
if (!isset($languageInfo['writing'])) {
$languageInfo['writing'] = null;
}
if ($onlyCodes) {
$result[] = $languageID;
} else {
$result[] = array_merge(array('id' => $languageID), $languageInfo);
}
}
}
}
return $result;
}
/**
* Return the population of a specific territory.
*
* @param string $territoryCode The territory code
*
* @return number|null Return the size of the population of the specified territory (or null if $territoryCode is not valid or no data is available)
*/
public static function getPopulation($territoryCode)
{
$result = null;
$info = self::getTerritoryInfo($territoryCode);
if (is_array($info)) {
$result = $info['population'];
}
return $result;
}
/**
* Return the literacy level for a specific territory, in %.
*
* @param string $territoryCode The territory code
*
* @return number|null Return the % of literacy lever of the specified territory (or null if $territoryCode is not valid or no data is available)
*/
public static function getLiteracyLevel($territoryCode)
{
$result = null;
$info = self::getTerritoryInfo($territoryCode);
if (is_array($info)) {
$result = $info['literacy'];
}
return $result;
}
/**
* Return the GDP (Gross Domestic Product) for a specific territory, in US$.
*
* @param string $territoryCode The territory code
*
* @return number|null Return the GDP of the specified territory (or null if $territoryCode is not valid or no data is available)
*/
public static function getGrossDomesticProduct($territoryCode)
{
$result = null;
$info = self::getTerritoryInfo($territoryCode);
if (is_array($info)) {
$result = $info['gdp'];
}
return $result;
}
/**
* Return a list of territory IDs where a specific language is spoken, sorted by the total number of people speaking that language.
*
* @param string $languageID The language identifier
* @param float $threshold The minimum percentage (from 0 to 100) to consider a language as spoken in a Country
*
* @return array
*/
public static function getTerritoriesForLanguage($languageID, $threshold = 0)
{
$peopleInTerritory = array();
foreach (Data::getGeneric('territoryInfo') as $territoryID => $territoryInfo) {
$percentage = null;
foreach ($territoryInfo['languages'] as $langID => $langInfo) {
if ((strcasecmp($languageID, $langID) === 0) || (stripos($langID, $languageID.'_') === 0)) {
if ($percentage === null) {
$percentage = $langInfo['population'];
} else {
$percentage += $langInfo['population'];
}
}
}
if ($percentage !== null && $percentage >= $threshold) {
$peopleInTerritory[$territoryID] = $territoryInfo['population'] * $percentage;
}
}
arsort($peopleInTerritory, SORT_NUMERIC);
$territoryIDs = array_keys($peopleInTerritory);
return $territoryIDs;
}
/**
* Return the code of the territory that contains a territory.
*
* @param string $childTerritoryCode
*
* @return string return the parent territory code, or an empty string if $childTerritoryCode is the World (001) or if it's invalid
*/
public static function getParentTerritoryCode($childTerritoryCode)
{
$result = '';
if (is_string($childTerritoryCode) && preg_match('/^[a-z0-9]{2,3}$/i', $childTerritoryCode)) {
$childTerritoryCode = strtoupper($childTerritoryCode);
foreach (Data::getGeneric('territoryContainment') as $parentTerritoryCode => $parentTerritoryInfo) {
if (in_array($childTerritoryCode, $parentTerritoryInfo['contains'], true)) {
$result = is_int($parentTerritoryCode) ? substr('00'.$parentTerritoryCode, -3) : $parentTerritoryCode;
if (($result === '001') || (strlen(static::getParentTerritoryCode($result)) > 0)) {
break;
}
}
}
}
return $result;
}
/**
* Retrieve the child territories of a parent territory.
*
* @param string $parentTerritoryCode
* @param bool $expandSubGroups set to true to expand the sub-groups, false to retrieve them
*
* @return array Return the list of territory codes that are children of $parentTerritoryCode (if $parentTerritoryCode is invalid you'll get an empty list)
*/
public static function getChildTerritoryCodes($parentTerritoryCode, $expandSubGroups = false)
{
$result = array();
if (is_string($parentTerritoryCode) && preg_match('/^[a-z0-9]{2,3}$/i', $parentTerritoryCode)) {
$parentTerritoryCode = strtoupper($parentTerritoryCode);
$data = Data::getGeneric('territoryContainment');
if (isset($data[$parentTerritoryCode])) {
$children = $data[$parentTerritoryCode]['contains'];
if ($expandSubGroups) {
foreach ($children as $child) {
$grandChildren = static::getChildTerritoryCodes($child, true);
if (empty($grandChildren)) {
$result[] = $child;
} else {
$result = array_merge($result, $grandChildren);
}
}
} else {
$result = $children;
}
}
}
return $result;
}
/**
* @param string $territoryCode
*
* @return array|null
*/
protected static function getTerritoryInfo($territoryCode)
{
$result = null;
if (preg_match('/^[a-z0-9]{2,3}$/i', $territoryCode)) {
$territoryCode = strtoupper($territoryCode);
$data = Data::getGeneric('territoryInfo');
if (isset($data[$territoryCode])) {
$result = $data[$territoryCode];
}
}
return $result;
}
/**
* @return array
*/
protected static function getStructure()
{
static $cache = null;
if ($cache === null) {
$data = Data::getGeneric('territoryContainment');
$result = static::fillStructure($data, '001', 0);
$cache = $result;
} else {
$result = $cache;
}
return $result;
}
/**
* @param array $data
* @param string $id
* @param int $level
*
* @return array
*/
protected static function fillStructure($data, $id, $level)
{
$item = array('id' => $id, 'level' => $level, 'children' => array());
if (isset($data[$id])) {
foreach ($data[$id]['contains'] as $childID) {
$item['children'][] = static::fillStructure($data, $childID, $level + 1);
}
}
return $item;
}
/**
* @param array $data
* @param array $list
* @param bool $flatList
*
* @return array
*/
protected static function finalizeWithNames($data, $list, $flatList)
{
$result = array();
foreach ($list as $item) {
$name = $data[$item['id']];
if ($flatList) {
$result[$item['id']] = $name;
} else {
$result[$item['id']] = array('name' => $name);
if (count($item['children']) > 0) {
$result[$item['id']]['children'] = static::finalizeWithNames($data, $item['children'], $flatList);
}
}
}
return $result;
}
/**
* @param array $parent
* @param int[] $levels
*
* @return array
*/
protected static function filterStructure($parent, $levels)
{
$thisResult = array();
if (in_array($parent['level'], $levels, true)) {
$thisResult[0] = $parent;
$thisResult[0]['children'] = array();
$addToSub = true;
} else {
$addToSub = false;
}
$subList = array();
foreach ($parent['children'] as $child) {
$subList = array_merge($subList, static::filterStructure($child, $levels));
}
if ($addToSub) {
$thisResult[0]['children'] = $subList;
} else {
$thisResult = $subList;
}
return $thisResult;
}
/**
* @param array $list
*
* @return array
*/
protected static function sort($list)
{
foreach (array_keys($list) as $i) {
if (isset($list[$i]['children'])) {
$list[$i]['children'] = static::sort($list[$i]['children']);
}
}
$sorter = new \Punic\Comparer();
uasort($list, function ($a, $b) use ($sorter) {
return $sorter->compare($a['name'], $b['name']);
});
return $list;
}
}