Punic APIs
  • Namespace
  • Class
  • Tree
  • Todo

Namespaces

  • Punic
    • Exception

Classes

  • Punic\Calendar
  • Punic\Comparer
  • Punic\Currency
  • Punic\Data
  • Punic\Language
  • Punic\Misc
  • Punic\Number
  • Punic\Phone
  • Punic\Plural
  • Punic\Territory
  • Punic\Unit

Exceptions

  • Punic\Exception
  • Punic\Exception\BadArgumentType
  • Punic\Exception\BadDataFileContents
  • Punic\Exception\DataFileNotFound
  • Punic\Exception\DataFileNotReadable
  • Punic\Exception\DataFolderNotFound
  • Punic\Exception\InvalidDataFile
  • Punic\Exception\InvalidLocale
  • Punic\Exception\NotImplemented
  • Punic\Exception\ValueNotInList
  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 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 
<?php

namespace Punic;

/**
 * Common data helper stuff.
 */
class Data
{
    /**
     * Let's cache already loaded files (locale-specific).
     *
     * @var array
     */
    protected static $cache = array();

    /**
     * Let's cache already loaded files (not locale-specific).
     *
     * @var array
     */
    protected static $cacheGeneric = array();

    /**
     * The current default locale.
     *
     * @var string
     */
    protected static $defaultLocale = 'en_US';

    /**
     * The fallback locale (used if default locale is not found).
     *
     * @var string
     */
    protected static $fallbackLocale = 'en_US';

    /**
     * Return the current default locale.
     *
     * @return string
     */
    public static function getDefaultLocale()
    {
        return static::$defaultLocale;
    }

    /**
     * Return the current default language.
     *
     * @return string
     */
    public static function getDefaultLanguage()
    {
        $info = static::explodeLocale(static::$defaultLocale);

        return $info['language'];
    }

    /**
     * Set the current default locale and language.
     *
     * @param string $locale
     *
     * @throws \Punic\Exception\InvalidLocale Throws an exception if $locale is not a valid string
     */
    public static function setDefaultLocale($locale)
    {
        if (static::explodeLocale($locale) === null) {
            throw new Exception\InvalidLocale($locale);
        }
        static::$defaultLocale = $locale;
    }

    /**
     * Return the current fallback locale (used if default locale is not found).
     *
     * @return string
     */
    public static function getFallbackLocale()
    {
        return static::$fallbackLocale;
    }

    /**
     * Return the current fallback language (used if default locale is not found).
     *
     * @return string
     */
    public static function getFallbackLanguage()
    {
        $info = static::explodeLocale(static::$fallbackLocale);

        return $info['language'];
    }

    /**
     * Set the current fallback locale and language.
     *
     * @param string $locale
     *
     * @throws \Punic\Exception\InvalidLocale Throws an exception if $locale is not a valid string
     */
    public static function setFallbackLocale($locale)
    {
        if (static::explodeLocale($locale) === null) {
            throw new Exception\InvalidLocale($locale);
        }
        if (static::$fallbackLocale !== $locale) {
            static::$fallbackLocale = $locale;
            static::$cache = array();
        }
    }

    /**
     * Get the locale data.
     *
     * @param string $identifier The data identifier
     * @param string $locale The locale identifier (if empty we'll use the current default locale)
     *
     * @throws \Punic\Exception Throws an exception in case of problems
     *
     * @return array
     *
     * @internal
     */
    public static function get($identifier, $locale = '')
    {
        if (!is_string($identifier) || $identifier === '') {
            throw new Exception\InvalidDataFile($identifier);
        }
        if (empty($locale)) {
            $locale = static::$defaultLocale;
        }
        if (!isset(static::$cache[$locale])) {
            static::$cache[$locale] = array();
        }
        if (!isset(static::$cache[$locale][$identifier])) {
            if (!@preg_match('/^[a-zA-Z0-9_\\-]+$/', $identifier)) {
                throw new Exception\InvalidDataFile($identifier);
            }
            $dir = static::getLocaleFolder($locale);
            if ($dir === '') {
                throw new Exception\DataFolderNotFound($locale, static::$fallbackLocale);
            }
            $file = $dir.DIRECTORY_SEPARATOR.$identifier.'.php';
            if (!is_file(__DIR__.DIRECTORY_SEPARATOR.$file)) {
                throw new Exception\DataFileNotFound($identifier, $locale, static::$fallbackLocale);
            }
            $data = include $file;
            //@codeCoverageIgnoreStart
            // In test enviro we can't replicate this problem
            if (!is_array($data)) {
                throw new Exception\BadDataFileContents($file, file_get_contents($file));
            }
            //@codeCoverageIgnoreEnd
            static::$cache[$locale][$identifier] = $data;
        }

        return static::$cache[$locale][$identifier];
    }

    /**
     * Get the generic data.
     *
     * @param string $identifier The data identifier
     *
     * @throws Exception Throws an exception in case of problems
     *
     * @return array
     *
     * @internal
     */
    public static function getGeneric($identifier)
    {
        if (!is_string($identifier) || $identifier === '') {
            throw new Exception\InvalidDataFile($identifier);
        }
        if (isset(static::$cacheGeneric[$identifier])) {
            return static::$cacheGeneric[$identifier];
        }
        if (!preg_match('/^[a-zA-Z0-9_\\-]+$/', $identifier)) {
            throw new Exception\InvalidDataFile($identifier);
        }
        $file = 'data'.DIRECTORY_SEPARATOR."$identifier.php";
        if (!is_file(__DIR__.DIRECTORY_SEPARATOR.$file)) {
            throw new Exception\DataFileNotFound($identifier);
        }
        $data = include $file;
        //@codeCoverageIgnoreStart
        // In test enviro we can't replicate this problem
        if (!is_array($data)) {
            throw new Exception\BadDataFileContents($file, file_get_contents($file));
        }
        //@codeCoverageIgnoreEnd
        static::$cacheGeneric[$identifier] = $data;

        return $data;
    }

    /**
     * Return a list of available locale identifiers.
     *
     * @param bool $allowGroups Set to true if you want to retrieve locale groups (eg. 'en-001'), false otherwise
     *
     * @return array
     */
    public static function getAvailableLocales($allowGroups = false)
    {
        $locales = array();
        $dir = __DIR__.DIRECTORY_SEPARATOR.'data';
        if (is_dir($dir) && is_readable($dir)) {
            $contents = @scandir($dir);
            if (is_array($contents)) {
                foreach (array_diff($contents, array('.', '..')) as $item) {
                    if (is_dir($dir.DIRECTORY_SEPARATOR.$item)) {
                        if ($item === 'root') {
                            $item = 'en-US';
                        }
                        $info = static::explodeLocale($item);
                        if (is_array($info)) {
                            if ((!$allowGroups) && preg_match('/^[0-9]{3}$/', $info['territory'])) {
                                foreach (Territory::getChildTerritoryCodes($info['territory'], true) as $territory) {
                                    if ($info['script'] !== '') {
                                        $locales[] = "{$info['language']}-{$info['script']}-$territory";
                                    } else {
                                        $locales[] = "{$info['language']}-$territory";
                                    }
                                }
                                $locales[] = $item;
                            } else {
                                $locales[] = $item;
                            }
                        }
                    }
                }
            }
        }

        return $locales;
    }

    /**
     * Try to guess the full locale (with script and territory) ID associated to a language.
     *
     * @param string $language The language identifier (if empty we'll use the current default language)
     * @param string $script The script identifier (if $language is empty we'll use the current default script)
     *
     * @return string Returns an empty string if the territory was not found, the territory ID otherwise
     */
    public static function guessFullLocale($language = '', $script = '')
    {
        $result = '';
        if (empty($language)) {
            $defaultInfo = static::explodeLocale(static::$defaultLocale);
            $language = $defaultInfo['language'];
            $script = $defaultInfo['script'];
        }
        $data = static::getGeneric('likelySubtags');
        $keys = array();
        if (!empty($script)) {
            $keys[] = "$language-$script";
        }
        $keys[] = $language;
        foreach ($keys as $key) {
            if (isset($data[$key])) {
                $result = $data[$key];
                if ($script !== '' && stripos($result, "$language-$script-") !== 0) {
                    $parts = static::explodeLocale($result);
                    if ($parts !== null) {
                        $result = "{$parts['language']}-$script-{$parts['territory']}";
                    }
                }
                break;
            }
        }

        return $result;
    }

    /**
     * Return the terrotory associated to the locale (guess it if it's not present in $locale).
     *
     * @param string $locale The locale identifier (if empty we'll use the current default locale)
     * @param bool $checkFallbackLocale Set to true to check the fallback locale if $locale (or the default locale) don't have an associated territory, false to don't fallback to fallback locale
     *
     * @return string
     */
    public static function getTerritory($locale = '', $checkFallbackLocale = true)
    {
        $result = '';
        if (empty($locale)) {
            $locale = static::$defaultLocale;
        }
        $info = static::explodeLocale($locale);
        if (is_array($info)) {
            if ($info['territory'] === '') {
                $fullLocale = static::guessFullLocale($info['language'], $info['script']);
                if ($fullLocale !== '') {
                    $info = static::explodeLocale($fullLocale);
                }
            }
            if ($info['territory'] !== '') {
                $result = $info['territory'];
            } elseif ($checkFallbackLocale) {
                $result = static::getTerritory(static::$fallbackLocale, false);
            }
        }

        return $result;
    }

    /**
     * Return the node associated to the locale territory.
     *
     * @param array $data The parent array for which you want the territory node
     * @param string $locale The locale identifier (if empty we'll use the current default locale)
     *
     * @return null|mixed Returns null if the node was not found, the node data otherwise
     *
     * @internal
     */
    public static function getTerritoryNode($data, $locale = '')
    {
        $result = null;
        $territory = static::getTerritory($locale);
        while ($territory !== '') {
            if (isset($data[$territory])) {
                $result = $data[$territory];
                break;
            }
            $territory = Territory::getParentTerritoryCode($territory);
        }

        return $result;
    }

    /**
     * Return the node associated to the language (not locale) territory.
     *
     * @param array $data The parent array for which you want the language node
     * @param string $locale The locale identifier (if empty we'll use the current default locale)
     *
     * @return null|mixed Returns null if the node was not found, the node data otherwise
     *
     * @internal
     */
    public static function getLanguageNode($data, $locale = '')
    {
        $result = null;
        if (empty($locale)) {
            $locale = static::$defaultLocale;
        }
        foreach (static::getLocaleAlternatives($locale) as $l) {
            if (isset($data[$l])) {
                $result = $data[$l];
                break;
            }
        }

        return $result;
    }

    /**
     * Returns the item of an array associated to a locale.
     *
     * @param array $data The data containing the locale info
     * @param string $locale The locale identifier (if empty we'll use the current default locale)
     *
     * @return null|mixed Returns null if $data is not an array or it does not contain locale info, the array item otherwise
     *
     * @internal
     */
    public static function getLocaleItem($data, $locale = '')
    {
        $result = null;
        if (is_array($data)) {
            if (empty($locale)) {
                $locale = static::$defaultLocale;
            }
            foreach (static::getLocaleAlternatives($locale) as $alternative) {
                if (isset($data[$alternative])) {
                    $result = $data[$alternative];
                    break;
                }
            }
        }

        return $result;
    }

    /**
     * Parse a string representing a locale and extract its components.
     *
     * @param string $locale
     *
     * @return null|string[] Return null if $locale is not valid; if $locale is valid returns an array with keys 'language', 'script', 'territory', 'parentLocale'
     *
     * @internal
     */
    public static function explodeLocale($locale)
    {
        $result = null;
        if (is_string($locale)) {
            if ($locale === 'root') {
                $locale = 'en-US';
            }
            $chunks = explode('-', str_replace('_', '-', strtolower($locale)));
            if (count($chunks) <= 3) {
                if (preg_match('/^[a-z]{2,3}$/', $chunks[0])) {
                    $language = $chunks[0];
                    $script = '';
                    $territory = '';
                    $parentLocale = '';
                    $ok = true;
                    $chunkCount = count($chunks);
                    for ($i = 1; $ok && ($i < $chunkCount); ++$i) {
                        if (preg_match('/^[a-z]{4}$/', $chunks[$i])) {
                            if ($script !== '') {
                                $ok = false;
                            } else {
                                $script = ucfirst($chunks[$i]);
                            }
                        } elseif (preg_match('/^([a-z]{2})|([0-9]{3})$/', $chunks[$i])) {
                            if ($territory !== '') {
                                $ok = false;
                            } else {
                                $territory = strtoupper($chunks[$i]);
                            }
                        } else {
                            $ok = false;
                        }
                    }
                    if ($ok) {
                        $parentLocales = static::getGeneric('parentLocales');
                        if ($script !== '' && $territory !== '' && isset($parentLocales["$language-$script-$territory"])) {
                            $parentLocale = $parentLocales["$language-$script-$territory"];
                        } elseif ($script !== '' && isset($parentLocales["$language-$script"])) {
                            $parentLocale = $parentLocales["$language-$script"];
                        } elseif ($territory !== '' && isset($parentLocales["$language-$territory"])) {
                            $parentLocale = $parentLocales["$language-$territory"];
                        } elseif (isset($parentLocales[$language])) {
                            $parentLocale = $parentLocales[$language];
                        }
                        $result = array(
                            'language' => $language,
                            'script' => $script,
                            'territory' => $territory,
                            'parentLocale' => $parentLocale,
                        );
                    }
                }
            }
        }

        return $result;
    }

    /**
     * @deprecated
     *
     * @param string $territory
     *
     * @return string
     */
    protected static function getParentTerritory($territory)
    {
        return Territory::getParentTerritoryCode($territory);
    }

    /**
     * @deprecated
     *
     * @param string $parentTerritory
     *
     * @return array
     */
    protected static function expandTerritoryGroup($parentTerritory)
    {
        return Territory::getChildTerritoryCodes($parentTerritory, true);
    }

    /**
     * Returns the path of the locale-specific data, looking also for the fallback locale.
     *
     * @param string $locale The locale for which you want the data folder
     *
     * @return string Returns an empty string if the folder is not found, the absolute path to the folder otherwise
     */
    protected static function getLocaleFolder($locale)
    {
        static $cache = array();
        $result = '';
        if (is_string($locale)) {
            $key = $locale.'/'.static::$fallbackLocale;
            if (!isset($cache[$key])) {
                foreach (static::getLocaleAlternatives($locale) as $alternative) {
                    $dir = 'data'.DIRECTORY_SEPARATOR.$alternative;
                    if (is_dir(__DIR__.DIRECTORY_SEPARATOR.$dir)) {
                        $result = $dir;
                        break;
                    }
                }
                $cache[$key] = $result;
            }
            $result = $cache[$key];
        }

        return $result;
    }

    /**
     * Returns a list of locale identifiers associated to a locale.
     *
     * @param string $locale The locale for which you want the alternatives
     * @param bool $addFallback Set to true to add the fallback locale to the result, false otherwise
     *
     * @return array
     */
    protected static function getLocaleAlternatives($locale, $addFallback = true)
    {
        $result = array();
        $localeInfo = static::explodeLocale($locale);
        if (!is_array($localeInfo)) {
            throw new Exception\InvalidLocale($locale);
        }
        $language = $localeInfo['language'];
        $script = $localeInfo['script'];
        $territory = $localeInfo['territory'];
        $parentLocale = $localeInfo['parentLocale'];
        if ($territory === '') {
            $fullLocale = static::guessFullLocale($language, $script);
            if ($fullLocale !== '') {
                $localeInfo = static::explodeLocale($fullLocale);
                $language = $localeInfo['language'];
                $script = $localeInfo['script'];
                $territory = $localeInfo['territory'];
                $parentLocale = $localeInfo['parentLocale'];
            }
        }
        $territories = array();
        while ($territory !== '') {
            $territories[] = $territory;
            $territory = Territory::getParentTerritoryCode($territory);
        }
        if ($script !== '') {
            foreach ($territories as $territory) {
                $result[] = "{$language}-{$script}-{$territory}";
            }
        }
        if ($script !== '') {
            $result[] = "{$language}-{$script}";
        }
        foreach ($territories as $territory) {
            $result[] = "{$language}-{$territory}";
            if ("{$language}-{$territory}" === 'en-US') {
                $result[] = 'root';
            }
        }
        if ($parentLocale !== '') {
            $result = array_merge($result, static::getLocaleAlternatives($parentLocale, false));
        }
        $result[] = $language;
        if ($addFallback && ($locale !== static::$fallbackLocale)) {
            $result = array_merge($result, static::getLocaleAlternatives(static::$fallbackLocale, false));
        }
        for ($i = count($result) - 1; $i > 1; --$i) {
            for ($j = 0; $j < $i; ++$j) {
                if ($result[$i] === $result[$j]) {
                    array_splice($result, $i, 1);
                    break;
                }
            }
        }
        $i = array_search('root', $result, true);
        if ($i !== false) {
            array_splice($result, $i, 1);
            $result[] = 'root';
        }

        return $result;
    }
}
Punic APIs API documentation generated by ApiGen