php-vn-lib/lib/locale.php

102 lines
2.1 KiB
PHP

<?php
namespace {
use Vn\Lib\Locale;
function i($stringId) {
echo Locale::getString($stringId);
}
function s($stringId) {
return Locale::getString($stringId);
}
}
namespace Vn\Lib {
class Locale {
static $localeSet = FALSE;
static $locale = 'en';
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))
$locale = self::$locale;
self::$locale = $locale;
setlocale(LC_ALL, $locale);
self::$localeSet = TRUE;
foreach (self::$paths as $path => $kk)
self::loadFile($path);
}
/**
* Gets the locale.
*
* @return string The locale with 2 digits format
*/
static function get() {
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]))
return self::$strings[$stringId];
else
return $stringId;
}
/**
* Adds a path where a JSON file with translations is located.
*
* @param string $path The JSON file path
*/
static function addPath($path) {
self::$paths[$path] = TRUE;
if (self::$localeSet)
self::loadFile($path);
}
/**
* Loads translations from a JSON file.
*
* @param string $path The JSON file path
*/
static function loadFile($path) {
$locale = self::$locale;
$file = stream_resolve_include_path("$path/locale/$locale.json");
if (file_exists($file)
&&($jsonString = file_get_contents($file)))
self::addTranslations(json_decode($jsonString, TRUE));
}
/**
* 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)
self::$strings[$string] = &$translation;
}
}
}