Translator.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. /**
  3. * This file is part of the Carbon package.
  4. *
  5. * (c) Brian Nesbitt <brian@nesbot.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Carbon;
  11. use Closure;
  12. use ReflectionException;
  13. use ReflectionFunction;
  14. use Symfony\Component\Translation;
  15. class Translator extends Translation\Translator
  16. {
  17. /**
  18. * Translator singletons for each language.
  19. *
  20. * @var array
  21. */
  22. protected static $singletons = [];
  23. /**
  24. * List of custom localized messages.
  25. *
  26. * @var array
  27. */
  28. protected $messages = [];
  29. /**
  30. * List of custom directories that contain translation files.
  31. *
  32. * @var string[]
  33. */
  34. protected $directories = [];
  35. /**
  36. * Set to true while constructing.
  37. *
  38. * @var bool
  39. */
  40. protected $initializing = false;
  41. /**
  42. * List of locales aliases.
  43. *
  44. * @var string[]
  45. */
  46. protected $aliases = [
  47. 'me' => 'sr_Latn_ME',
  48. 'scr' => 'sh',
  49. ];
  50. /**
  51. * Return a singleton instance of Translator.
  52. *
  53. * @param string|null $locale optional initial locale ("en" - english by default)
  54. *
  55. * @return static
  56. */
  57. public static function get($locale = null)
  58. {
  59. $locale = $locale ?: 'en';
  60. if (!isset(static::$singletons[$locale])) {
  61. static::$singletons[$locale] = new static($locale ?: 'en');
  62. }
  63. return static::$singletons[$locale];
  64. }
  65. public function __construct($locale, Translation\Formatter\MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false)
  66. {
  67. $this->initializing = true;
  68. $this->directories = [__DIR__.'/Lang'];
  69. $this->addLoader('array', new Translation\Loader\ArrayLoader());
  70. parent::__construct($locale, $formatter, $cacheDir, $debug);
  71. $this->initializing = false;
  72. }
  73. /**
  74. * Returns the list of directories translation files are searched in.
  75. *
  76. * @return array
  77. */
  78. public function getDirectories(): array
  79. {
  80. return $this->directories;
  81. }
  82. /**
  83. * Set list of directories translation files are searched in.
  84. *
  85. * @param array $directories new directories list
  86. *
  87. * @return $this
  88. */
  89. public function setDirectories(array $directories)
  90. {
  91. $this->directories = $directories;
  92. return $this;
  93. }
  94. /**
  95. * Add a directory to the list translation files are searched in.
  96. *
  97. * @param string $directory new directory
  98. *
  99. * @return $this
  100. */
  101. public function addDirectory(string $directory)
  102. {
  103. $this->directories[] = $directory;
  104. return $this;
  105. }
  106. /**
  107. * Remove a directory from the list translation files are searched in.
  108. *
  109. * @param string $directory directory path
  110. *
  111. * @return $this
  112. */
  113. public function removeDirectory(string $directory)
  114. {
  115. $search = rtrim(strtr($directory, '\\', '/'), '/');
  116. return $this->setDirectories(array_filter($this->getDirectories(), function ($item) use ($search) {
  117. return rtrim(strtr($item, '\\', '/'), '/') !== $search;
  118. }));
  119. }
  120. /**
  121. * Returns the translation.
  122. *
  123. * @param string $id
  124. * @param array $parameters
  125. * @param string $domain
  126. * @param string $locale
  127. *
  128. * @return string
  129. */
  130. public function trans($id, array $parameters = [], $domain = null, $locale = null)
  131. {
  132. if ($domain === null) {
  133. $domain = 'messages';
  134. }
  135. $format = $this->getCatalogue($locale)->get((string) $id, $domain);
  136. if ($format instanceof Closure) {
  137. // @codeCoverageIgnoreStart
  138. try {
  139. $count = (new ReflectionFunction($format))->getNumberOfRequiredParameters();
  140. } catch (ReflectionException $exception) {
  141. $count = 0;
  142. }
  143. // @codeCoverageIgnoreEnd
  144. return $format(
  145. ...array_values($parameters),
  146. ...array_fill(0, max(0, $count - \count($parameters)), null)
  147. );
  148. }
  149. return parent::trans($id, $parameters, $domain, $locale);
  150. }
  151. /**
  152. * Reset messages of a locale (all locale if no locale passed).
  153. * Remove custom messages and reload initial messages from matching
  154. * file in Lang directory.
  155. *
  156. * @param string|null $locale
  157. *
  158. * @return bool
  159. */
  160. public function resetMessages($locale = null)
  161. {
  162. if ($locale === null) {
  163. $this->messages = [];
  164. return true;
  165. }
  166. foreach ($this->getDirectories() as $directory) {
  167. $data = @include sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale);
  168. if ($data !== false) {
  169. $this->messages[$locale] = $data;
  170. $this->addResource('array', $this->messages[$locale], $locale);
  171. return true;
  172. }
  173. }
  174. return false;
  175. }
  176. /**
  177. * Returns the list of files matching a given locale prefix (or all if empty).
  178. *
  179. * @param string $prefix prefix required to filter result
  180. *
  181. * @return array
  182. */
  183. public function getLocalesFiles($prefix = '')
  184. {
  185. $files = [];
  186. foreach ($this->getDirectories() as $directory) {
  187. $directory = rtrim($directory, '\\/');
  188. foreach (glob("$directory/$prefix*.php") as $file) {
  189. $files[] = $file;
  190. }
  191. }
  192. return array_unique($files);
  193. }
  194. /**
  195. * Returns the list of internally available locales and already loaded custom locales.
  196. * (It will ignore custom translator dynamic loading.)
  197. *
  198. * @param string $prefix prefix required to filter result
  199. *
  200. * @return array
  201. */
  202. public function getAvailableLocales($prefix = '')
  203. {
  204. $locales = [];
  205. foreach ($this->getLocalesFiles($prefix) as $file) {
  206. $locales[] = substr($file, strrpos($file, '/') + 1, -4);
  207. }
  208. return array_unique(array_merge($locales, array_keys($this->messages)));
  209. }
  210. /**
  211. * Init messages language from matching file in Lang directory.
  212. *
  213. * @param string $locale
  214. *
  215. * @return bool
  216. */
  217. protected function loadMessagesFromFile($locale)
  218. {
  219. if (isset($this->messages[$locale])) {
  220. return true;
  221. }
  222. return $this->resetMessages($locale);
  223. }
  224. /**
  225. * Set messages of a locale and take file first if present.
  226. *
  227. * @param string $locale
  228. * @param array $messages
  229. *
  230. * @return $this
  231. */
  232. public function setMessages($locale, $messages)
  233. {
  234. $this->loadMessagesFromFile($locale);
  235. $this->addResource('array', $messages, $locale);
  236. $this->messages[$locale] = array_merge(
  237. isset($this->messages[$locale]) ? $this->messages[$locale] : [],
  238. $messages
  239. );
  240. return $this;
  241. }
  242. /**
  243. * Set messages of the current locale and take file first if present.
  244. *
  245. * @param array $messages
  246. *
  247. * @return $this
  248. */
  249. public function setTranslations($messages)
  250. {
  251. return $this->setMessages($this->getLocale(), $messages);
  252. }
  253. /**
  254. * Get messages of a locale, if none given, return all the
  255. * languages.
  256. *
  257. * @param string|null $locale
  258. *
  259. * @return array
  260. */
  261. public function getMessages($locale = null)
  262. {
  263. return $locale === null ? $this->messages : $this->messages[$locale];
  264. }
  265. /**
  266. * Set the current translator locale and indicate if the source locale file exists
  267. *
  268. * @param string $locale locale ex. en
  269. *
  270. * @return bool
  271. */
  272. public function setLocale($locale)
  273. {
  274. $locale = preg_replace_callback('/[-_]([a-z]{2,}|[0-9]{2,})/', function ($matches) {
  275. // _2-letters or YUE is a region, _3+-letters is a variant
  276. $upper = strtoupper($matches[1]);
  277. if ($upper === 'YUE' || $upper === 'ISO' || \strlen($upper) < 3) {
  278. return "_$upper";
  279. }
  280. return '_'.ucfirst($matches[1]);
  281. }, strtolower($locale));
  282. $previousLocale = $this->getLocale();
  283. if ($previousLocale === $locale && isset($this->messages[$locale])) {
  284. return true;
  285. }
  286. unset(static::$singletons[$previousLocale]);
  287. if ($locale === 'auto') {
  288. $completeLocale = setlocale(LC_TIME, '0');
  289. $locale = preg_replace('/^([^_.-]+).*$/', '$1', $completeLocale);
  290. $locales = $this->getAvailableLocales($locale);
  291. $completeLocaleChunks = preg_split('/[_.-]+/', $completeLocale);
  292. $getScore = function ($language) use ($completeLocaleChunks) {
  293. return static::compareChunkLists($completeLocaleChunks, preg_split('/[_.-]+/', $language));
  294. };
  295. usort($locales, function ($first, $second) use ($getScore) {
  296. return $getScore($second) <=> $getScore($first);
  297. });
  298. $locale = $locales[0];
  299. }
  300. if (isset($this->aliases[$locale])) {
  301. $locale = $this->aliases[$locale];
  302. }
  303. // If subtag (ex: en_CA) first load the macro (ex: en) to have a fallback
  304. if (str_contains($locale, '_') &&
  305. $this->loadMessagesFromFile($macroLocale = preg_replace('/^([^_]+).*$/', '$1', $locale))
  306. ) {
  307. parent::setLocale($macroLocale);
  308. }
  309. if ($this->loadMessagesFromFile($locale) || $this->initializing) {
  310. parent::setLocale($locale);
  311. return true;
  312. }
  313. return false;
  314. }
  315. /**
  316. * Show locale on var_dump().
  317. *
  318. * @return array
  319. */
  320. public function __debugInfo()
  321. {
  322. return [
  323. 'locale' => $this->getLocale(),
  324. ];
  325. }
  326. private static function compareChunkLists($referenceChunks, $chunks)
  327. {
  328. $score = 0;
  329. foreach ($referenceChunks as $index => $chunk) {
  330. if (!isset($chunks[$index])) {
  331. $score++;
  332. continue;
  333. }
  334. if (strtolower($chunks[$index]) === strtolower($chunk)) {
  335. $score += 10;
  336. }
  337. }
  338. return $score;
  339. }
  340. }