ILIAS  trunk Revision v12.0_alpha-377-g3641b37b9db
Translator.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
24
29class Translator
30{
31 private bool $internal = false;
32 private const LANG_PHP = 'lang.php';
33
34 private MultiLanguage $multi_language;
35 private string $prefix;
36
37 public function __construct(
38 private \ilLanguage $lng,
39 ?TranslationsRepository $translations_repository = null,
40 string ...$module
41 ) {
42 $this->prefix = ''; // $module[0] ?? ''; // Disabled auto prefixing for now
43 foreach ($module as $m) {
44 $this->lng->loadLanguageModule($m);
45 }
46 $this->multi_language = new MultiLanguage($translations_repository);
47 }
48
49 public function t(string $identifier, ?string $prefix = null, array $subsitutions = []): string
50 {
51 return $this->translate($identifier, $prefix, $subsitutions);
52 }
53
57 public function txt(string $identifier, array $subsitutions = []): string
58 {
59 return $this->translate($identifier, null, $subsitutions);
60 }
61
62 public function translate(string $identifier, ?string $prefix = null, array $subsitutions = []): string
63 {
64 $key = $prefix !== null ? $prefix . '_' . $identifier : $identifier;
65
66 if (!empty($this->prefix)) {
67 $key = $this->prefix . '_' . $key;
68 }
69
70 if ($subsitutions !== []) {
71 return sprintf($this->internal($key, $this->lng->txt($key)), ...array_values($subsitutions));
72 }
73
74 return $this->internal($key, $this->lng->txt($key));
75 }
76
77 public function setGeneralPrefix(string $prefix): void
78 {
79 $this->prefix = $prefix;
80 }
81
82 public function ml(): MultiLanguage
83 {
84 return $this->multi_language;
85 }
86
87 private function internal(string $key, string $translation): string
88 {
89 if (!$this->internal) {
90 return $translation;
91 }
92
93 $file = __DIR__ . '/' . self::LANG_PHP;
94 touch($file);
95 $current = (array) ((@include $file) ?? []);
96 $untranslated = ($translation === '-' . $key . '-') || ($translation === $key);
97
98 // Missing
99 if (!($current[$key] ?? false)) {
100 $current[$key] = $translation = $key;
101 asort($current);
102 file_put_contents($file, '<?php return ' . var_export($current, true) . ';');
103 return $translation;
104 }
105
106 if ($untranslated || ($current[$key] ?? $translation) !== $translation) {
107 return $current[$key] ?? $translation;
108 }
109
110 return $translation;
111 }
112
113}
__construct()
Constructor setup ILIAS global object @access public.
Definition: class.ilias.php:76
language handling
global $lng
Definition: privfeed.php:31