php-vn-lib/lib/locale.php

101 lines
2.0 KiB
PHP
Raw Normal View History

2015-01-23 12:38:29 +00:00
<?php
namespace {
2015-01-23 12:38:29 +00:00
use Vn\Lib\Locale;
function i($stringId) {
echo Locale::getString($stringId);
2015-01-23 12:38:29 +00:00
}
function s($stringId) {
return Locale::getString($stringId);
2015-01-23 12:38:29 +00:00
}
}
namespace Vn\Lib {
class Locale {
2015-01-23 12:38:29 +00:00
static $localeSet = FALSE;
static $locale = 'en';
2015-01-23 12:38:29 +00:00
static $strings = [];
static $paths = [];
/**
* Sets the locale.
*
* @param string $locale The locale with 2 digits format, or %NULL to
* set the default
*/
static function set($locale = NULL) {
if (empty($locale))
2015-01-23 12:38:29 +00:00
$locale = self::$locale;
self::$locale = $locale;
setlocale(LC_ALL, $locale);
2015-01-23 12:38:29 +00:00
self::$localeSet = TRUE;
2015-02-08 15:39:22 +00:00
foreach (self::$paths as $path => $kk)
self::loadFile($path);
2015-01-23 12:38:29 +00:00
}
/**
* Gets the locale.
*
* @return string The locale with 2 digits format
*/
static function get() {
2015-01-23 12:38:29 +00:00
return self::$locale;
}
/**
* Gets the translation of a string, if no translation is found the same
* string is returned.
*
* @param string $stringId The string to translate
* @return string The translated string
*/
static function getString($stringId) {
if (isset(self::$strings[$stringId]))
2015-01-23 12:38:29 +00:00
return self::$strings[$stringId];
else
return $stringId;
}
/**
* Adds a path where a YAML file with translations is located.
2015-01-23 12:38:29 +00:00
*
* @param string $path The YAML file path
*/
static function addPath($path) {
2015-01-23 12:38:29 +00:00
self::$paths[$path] = TRUE;
2015-02-08 15:39:22 +00:00
2015-01-23 12:38:29 +00:00
if (self::$localeSet)
self::loadFile($path);
2015-01-23 12:38:29 +00:00
}
/**
* Loads translations from a YAML file.
2015-01-23 12:38:29 +00:00
*
* @param string $path The YAML file path
*/
static function loadFile($path) {
2016-10-27 11:30:32 +00:00
$locale = self::$locale;
$file = stream_resolve_include_path("$path/locale/$locale.yml");
2015-01-23 12:38:29 +00:00
if (file_exists($file))
self::addTranslations(\yaml_parse_file($file));
2015-01-23 12:38:29 +00:00
}
/**
* Adds a set of translations to the database.
*
* @param array $strings Associative array of every string and its
* translation
*/
static function addTranslations($strings) {
foreach ($strings as $string => &$translation)
2015-01-23 12:38:29 +00:00
self::$strings[$string] = &$translation;
}
}
}