The clean & modern RSS server that doesn't give you any crap. https://thearsse.com/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Lang.php 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  2. /** @license MIT
  3. * Copyright 2017 J. King, Dustin Wilson et al.
  4. * See LICENSE and AUTHORS files for details */
  5. declare(strict_types=1);
  6. namespace JKingWeb\Arsse;
  7. class Lang {
  8. const DEFAULT = "en"; // fallback locale
  9. const REQUIRED = [ // collection of absolutely required strings to handle pathological errors
  10. 'Exception.JKingWeb/Arsse/Exception.uncoded' => 'The specified exception symbol {0} has no code specified in AbstractException.php',
  11. 'Exception.JKingWeb/Arsse/Exception.unknown' => 'An unknown error has occurred',
  12. 'Exception.JKingWeb/Arsse/Lang/Exception.defaultFileMissing' => 'Default language file "{0}" missing',
  13. 'Exception.JKingWeb/Arsse/Lang/Exception.fileMissing' => 'Language file "{0}" is not available',
  14. 'Exception.JKingWeb/Arsse/Lang/Exception.fileUnreadable' => 'Insufficient permissions to read language file "{0}"',
  15. 'Exception.JKingWeb/Arsse/Lang/Exception.fileCorrupt' => 'Language file "{0}" is corrupt or does not conform to expected format',
  16. 'Exception.JKingWeb/Arsse/Lang/Exception.stringMissing' => 'Message string "{msgID}" missing from all loaded language files ({fileList})',
  17. 'Exception.JKingWeb/Arsse/Lang/Exception.stringInvalid' => 'Message string "{msgID}" is not a valid ICU message string (language files loaded: {fileList})',
  18. ];
  19. public $path; // path to locale files; this is a public property to facilitate unit testing
  20. protected $requirementsMet = false; // whether the Intl extension is loaded
  21. protected $synched = false; // whether the wanted locale is actually loaded (lazy loading is used by default)
  22. protected $wanted = self::DEFAULT; // the currently requested locale
  23. protected $locale = ""; // the currently loaded locale
  24. protected $loaded = []; // the cascade of loaded locale file names
  25. protected $strings = self::REQUIRED; // the loaded locale strings, merged
  26. public function __construct(string $path = BASE."locale".DIRECTORY_SEPARATOR) {
  27. $this->path = $path;
  28. }
  29. public function set(string $locale, bool $immediate = false): string {
  30. // make sure the Intl extension is loaded
  31. if (!$this->requirementsMet) {
  32. $this->checkRequirements();
  33. }
  34. // if requesting the same locale as already wanted, just return (but load first if we've requested an immediate load)
  35. if ($locale==$this->wanted) {
  36. if ($immediate && !$this->synched) {
  37. $this->load();
  38. }
  39. return $locale;
  40. }
  41. // if we've requested a locale other than the null locale, fetch the list of available files and find the closest match e.g. en_ca_somedialect -> en_ca
  42. if ($locale != "") {
  43. $list = $this->listFiles();
  44. // if the default locale is unavailable, this is (for now) an error
  45. if (!in_array(self::DEFAULT, $list)) {
  46. throw new Lang\Exception("defaultFileMissing", self::DEFAULT);
  47. }
  48. $this->wanted = $this->match($locale, $list);
  49. } else {
  50. $this->wanted = "";
  51. }
  52. $this->synched = false;
  53. // load right now if asked to, otherwise load later when actually required
  54. if ($immediate) {
  55. $this->load();
  56. }
  57. return $this->wanted;
  58. }
  59. public function get(bool $loaded = false): string {
  60. // we can either return the wanted locale (default) or the currently loaded locale
  61. return $loaded ? $this->locale : $this->wanted;
  62. }
  63. public function dump(): array {
  64. return $this->strings;
  65. }
  66. public function msg(string $msgID, $vars = null): string {
  67. return $this($msgID, $vars);
  68. }
  69. public function __invoke(string $msgID, $vars = null): string {
  70. // if we're trying to load the system default language and it fails, we have a chicken and egg problem, so we catch the exception and load no language file instead
  71. if (!$this->synched) {
  72. try {
  73. $this->load();
  74. } catch (Lang\Exception $e) {
  75. if ($this->wanted==self::DEFAULT) {
  76. $this->set("", true);
  77. } else {
  78. throw $e;
  79. }
  80. }
  81. }
  82. // if the requested message is not present in any of the currently loaded language files, throw an exception
  83. // note that this is indicative of a programming error since the default locale should have all strings
  84. if (!array_key_exists($msgID, $this->strings)) {
  85. throw new Lang\Exception("stringMissing", ['msgID' => $msgID, 'fileList' => implode(", ", $this->loaded)]);
  86. }
  87. $msg = $this->strings[$msgID];
  88. // variables fed to MessageFormatter must be contained in an array
  89. if ($vars===null) {
  90. // even though strings not given parameters will not get formatted, we do not optimize this case away: we still want to catch invalid strings
  91. $vars = [];
  92. } elseif (!is_array($vars)) {
  93. $vars = [$vars];
  94. }
  95. $msg = \MessageFormatter::formatMessage($this->locale, $msg, $vars);
  96. if ($msg===false) {
  97. throw new Lang\Exception("stringInvalid", ['msgID' => $msgID, 'fileList' => implode(", ", $this->loaded)]);
  98. }
  99. return $msg;
  100. }
  101. public function list(string $locale = ""): array {
  102. $out = [];
  103. $files = $this->listFiles();
  104. foreach ($files as $tag) {
  105. $out[$tag] = \Locale::getDisplayName($tag, ($locale=="") ? $tag : $locale);
  106. }
  107. return $out;
  108. }
  109. public function match(string $locale, array $list = null): string {
  110. $list = $list ?? $this->listFiles();
  111. $default = ($this->locale=="") ? self::DEFAULT : $this->locale;
  112. return \Locale::lookup($list, $locale, true, $default);
  113. }
  114. protected function checkRequirements(): bool {
  115. if (!extension_loaded("intl")) {
  116. throw new ExceptionFatal("The \"Intl\" extension is required, but not loaded"); // @codeCoverageIgnore
  117. }
  118. $this->requirementsMet = true;
  119. return true;
  120. }
  121. /** @codeCoverageIgnore */
  122. protected function globFiles(string $path): array {
  123. // we wrap PHP's glob function in this method so that unit tests may override it
  124. return glob($path."*.php");
  125. }
  126. protected function listFiles(): array {
  127. $out = $this->globFiles($this->path."*.php");
  128. // trim the returned file paths to return just the language tag
  129. $out = array_map(function($file) {
  130. $file = str_replace(DIRECTORY_SEPARATOR, "/", $file); // we replace the directory separator because we don't use native paths in testing
  131. $file = substr($file, strrpos($file, "/")+1);
  132. return strtolower(substr($file, 0, strrpos($file, ".")));
  133. }, $out);
  134. // sort the results
  135. natsort($out);
  136. return $out;
  137. }
  138. protected function load(): bool {
  139. if (!$this->requirementsMet) {
  140. $this->checkRequirements();
  141. }
  142. // if we've requested no locale (""), just load the fallback strings and return
  143. if ($this->wanted=="") {
  144. $this->strings = self::REQUIRED;
  145. $this->locale = $this->wanted;
  146. $this->synched = true;
  147. return true;
  148. }
  149. // decompose the requested locale from specific to general, building a list of files to load
  150. $tags = \Locale::parseLocale($this->wanted);
  151. $files = [];
  152. while (sizeof($tags) > 0) {
  153. $files[] = strtolower(\Locale::composeLocale($tags));
  154. $tag = array_pop($tags);
  155. }
  156. // include the default locale as the base if the most general locale requested is not the default
  157. if ($tag != self::DEFAULT) {
  158. $files[] = self::DEFAULT;
  159. }
  160. // save the list of files to be loaded for later reference
  161. $loaded = $files;
  162. // reduce the list of files to be loaded to the minimum necessary (e.g. if we go from "fr" to "fr_ca", we don't need to load "fr" or "en")
  163. $files = [];
  164. foreach ($loaded as $file) {
  165. if ($file==$this->locale) {
  166. break;
  167. }
  168. $files[] = $file;
  169. }
  170. // if we need to load all files, start with the fallback strings
  171. $strings = [];
  172. if ($files==$loaded) {
  173. $strings[] = self::REQUIRED;
  174. } else {
  175. // otherwise start with the strings we already have if we're going from e.g. "fr" to "fr_ca"
  176. $strings[] = $this->strings;
  177. }
  178. // read files in reverse order
  179. $files = array_reverse($files);
  180. foreach ($files as $file) {
  181. if (!file_exists($this->path."$file.php")) {
  182. throw new Lang\Exception("fileMissing", $file);
  183. } elseif (!is_readable($this->path."$file.php")) {
  184. throw new Lang\Exception("fileUnreadable", $file);
  185. }
  186. try {
  187. // we use output buffering in case the language file is corrupted
  188. ob_start();
  189. $arr = (include $this->path."$file.php");
  190. } catch (\Throwable $e) {
  191. $arr = null;
  192. } finally {
  193. ob_end_clean();
  194. }
  195. if (!is_array($arr)) {
  196. throw new Lang\Exception("fileCorrupt", $file);
  197. }
  198. $strings[] = $arr;
  199. }
  200. // apply the results and return
  201. $this->strings = call_user_func_array("array_replace_recursive", $strings);
  202. $this->loaded = $loaded;
  203. $this->locale = $this->wanted;
  204. $this->synched = true;
  205. return true;
  206. }
  207. }