openvk/Web/Util/Localizator.php

79 lines
2.3 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2020-06-07 19:04:43 +03:00
namespace openvk\Web\Util;
2020-06-07 19:04:43 +03:00
use Chandler\Patterns\TSimpleSingleton;
class Localizator
{
use TSimpleSingleton;
public const DEFAULT_LANG = "ru";
2020-06-07 19:04:43 +03:00
private function __construct() {}
2020-06-07 19:04:43 +03:00
protected function _getIncludes($string): array
{
$includes = [];
$matches = [];
preg_match_all("%^#([A-z]++) <([A-z0-9_ -]+)>$%Xm", $string, $matches);
for ($i = 0; $i < sizeof($matches[1]); $i++) {
2020-06-07 19:04:43 +03:00
$directive = $matches[1][$i];
if ($directive === "include") {
2020-06-07 19:04:43 +03:00
$includes[] = dirname(__FILE__) . "/../../locales/" . $matches[2][$i] . ".strings";
} else {
trigger_error("Unknown preprocessor directive \"$directive\" in locale file, skipping.
This will throw an error in a future version of Localizator::_getIncludes.", E_USER_DEPRECATED);
}
}
2020-06-07 19:04:43 +03:00
return $includes;
}
2020-06-07 19:04:43 +03:00
protected function parse($file): array
{
$hash = sha1($file);
if (isset($GLOBALS["localizationCache_$hash"])) {
return $GLOBALS["localizationCache_$hash"];
}
2020-06-07 19:04:43 +03:00
$string = file_get_contents($file);
$string = preg_replace("%^\/\*.*\*\/\r?$%m", "", $string); #Remove comments
2020-06-07 19:04:43 +03:00
$array = [];
foreach (preg_split("%;[\\r\\n]++%", $string) as $statement) {
2020-06-07 19:04:43 +03:00
$s = explode(" = ", trim($statement));
2020-06-07 19:04:43 +03:00
try {
$array[eval("return $s[0];")] = eval("return $s[1];");
} catch (\ParseError $ex) {
throw new \ParseError($ex->getMessage() . " near " . $s[0]);
2020-06-07 19:04:43 +03:00
}
}
foreach (self::_getIncludes($string) as $include) {
2020-06-07 19:04:43 +03:00
$array = array_merge(@self::parse($include), $array);
}
2020-06-07 19:04:43 +03:00
$GLOBALS["localizationCache_$hash"] = $array;
return $array;
}
public function _($id, $lang = null): string
2020-06-07 19:04:43 +03:00
{
$lang = is_null($lang) ? static::DEFAULT_LANG : $lang;
$array = @self::parse(dirname(__FILE__) . "/../../locales/$lang.strings");
return $array[$id] ?? "@$id";
2020-06-07 19:04:43 +03:00
}
public function export($lang = null): ?array
2021-12-04 16:06:28 +03:00
{
$lang = is_null($lang) ? static::DEFAULT_LANG : $lang;
$array = @self::parse(dirname(__FILE__) . "/../../locales/$lang.strings");
return $array;
}
2020-06-07 19:04:43 +03:00
}