Debian Codegraph @

vendor/ipl/i18n/src/GettextTranslator.php

raw
1 <?php
2
3 namespace ipl\I18n;
4
5 use Exception;
6 use FilesystemIterator;
7 use ipl\Stdlib\Contract\Translator;
8 use Locale;
9 use SplFileInfo;
10
11 /**
12 * Translator using PHP's native [gettext](https://www.php.net/gettext) extension
13 *
14 * # Example Usage
15 *
16 * $translator = (new GettextTranslator())
17 * ->addTranslationDirectory('/path/to/locales')
18 * ->addTranslationDirectory('/path/to/locales-of-domain', 'special') // Can be the same directory as above.
19 * ->setLocale('de_DE');
20 *
21 * $translator->translate('user');
22 *
23 * printf(
24 * $translator->translatePlural('%d user', '%d user', 42),
25 * 42
26 * );
27 *
28 * $translator->translateInDomain('special-domain', 'request');
29 *
30 * printf(
31 * $translator->translatePluralInDomain('special-domain', '%d request', '%d requests', 42),
32 * 42
33 * );
34 *
35 * // All translation functions also accept a context as last parameter.
36 * $translator->translate('group', 'a-context');
37 *
38 */
39 class GettextTranslator implements Translator
40 {
41 /** @var string Default gettext domain */
42 protected string $defaultDomain = 'default';
43
44 /** @var string Default locale code */
45 protected string $defaultLocale = 'en_US';
46
47 /** @var array<string, string> Known translation directories as array[$domain] => $directory */
48 protected array $translationDirectories = [];
49
50 /** @var array<string, string> Loaded translations as array[$domain] => $directory */
51 protected array $loadedTranslations = [];
52
53 /** @var ?string Primary locale code used for translations */
54 protected ?string $locale = null;
55
56 /**
57 * Get the default domain
58 *
59 * @return string
60 */
61 public function getDefaultDomain(): string
62 {
63 return $this->defaultDomain;
64 }
65
66 /**
67 * Set the default domain
68 *
69 * @param string $defaultDomain
70 *
71 * @return $this
72 */
73 public function setDefaultDomain(string $defaultDomain): static
74 {
75 $this->defaultDomain = $defaultDomain;
76
77 return $this;
78 }
79
80 /**
81 * Get the default locale
82 *
83 * @return string
84 */
85 public function getDefaultLocale(): string
86 {
87 return $this->defaultLocale;
88 }
89
90 /**
91 * Set the default locale
92 *
93 * @param string $defaultLocale
94 *
95 * @return $this
96 */
97 public function setDefaultLocale(string $defaultLocale): static
98 {
99 $this->defaultLocale = $defaultLocale;
100
101 return $this;
102 }
103
104 /**
105 * Get available translations
106 *
107 * @return array<string, string> Available translations as array[$domain] => $directory
108 */
109 public function getTranslationDirectories(): array
110 {
111 return $this->translationDirectories;
112 }
113
114 /**
115 * Add a translation directory
116 *
117 * @param string $directory Path to translation files
118 * @param ?string $domain Optional domain of the translation
119 *
120 * @return $this
121 */
122 public function addTranslationDirectory(string $directory, ?string $domain = null): static
123 {
124 $this->translationDirectories[$domain ?: $this->defaultDomain] = $directory;
125
126 return $this;
127 }
128
129 /**
130 * Get loaded translations
131 *
132 * @return array<string, string> Loaded translations as array[$domain] => $directory
133 */
134 public function getLoadedTranslations(): array
135 {
136 return $this->loadedTranslations;
137 }
138
139 /**
140 * Load a translation so that gettext is able to locate its message catalogs
141 *
142 * {@see bindtextdomain()} is called internally for every domain and path
143 * that has been added with {@see addTranslationDirectory()}.
144 *
145 * @return $this
146 * @throws Exception If {@see bindtextdomain()} fails for a domain
147 */
148 public function loadTranslations(): static
149 {
150 foreach ($this->translationDirectories as $domain => $directory) {
151 if (
152 isset($this->loadedTranslations[$domain])
153 && $this->loadedTranslations[$domain] === $directory
154 ) {
155 continue;
156 }
157
158 if (bindtextdomain($domain, $directory) !== $directory) {
159 throw new Exception(sprintf(
160 "Can't register domain '%s' with path '%s'",
161 $domain,
162 $directory
163 ));
164 }
165
166 bind_textdomain_codeset($domain, 'UTF-8');
167
168 $this->loadedTranslations[$domain] = $directory;
169 }
170
171 return $this;
172 }
173
174 /**
175 * Get the primary locale code used for translations
176 *
177 * @return ?string
178 */
179 public function getLocale(): ?string
180 {
181 return $this->locale;
182 }
183
184 /**
185 * Set up the primary locale code to use for translations
186 *
187 * Calls {@see loadTranslations()} internally.
188 *
189 * @param string $locale Locale code
190 *
191 * @return $this
192 * @throws Exception If {@see bindtextdomain()} fails for a domain
193 */
194 public function setLocale(string $locale): static
195 {
196 putenv("LANGUAGE=$locale.UTF-8");
197 setlocale(LC_ALL, $locale . '.UTF-8');
198 Locale::setDefault($locale . '.UTF-8');
199
200 $this->loadTranslations();
201
202 textdomain($this->getDefaultDomain());
203
204 $this->locale = $locale;
205
206 return $this;
207 }
208
209 /**
210 * Encode a message with context to the representation used in .mo files
211 *
212 * @param string $message
213 * @param string $context
214 *
215 * @return string The encoded message as context + "\x04" + message
216 */
217 public function encodeMessageWithContext(string $message, string $context): string
218 {
219 // .mo format: context + "\x04" + message (gettext >= 0.15).
220 return "{$context}\x04{$message}";
221 }
222
223 public function translate(string $message, ?string $context = null): string
224 {
225 if ($context !== null) {
226 $messageForGettext = $this->encodeMessageWithContext($message, $context);
227 } else {
228 $messageForGettext = $message;
229 }
230
231 $translation = gettext($messageForGettext);
232
233 if ($translation === $messageForGettext) {
234 return $message;
235 }
236
237 return $translation;
238 }
239
240 public function translateInDomain(string $domain, string $message, ?string $context = null): string
241 {
242 if ($context !== null) {
243 $messageForGettext = $this->encodeMessageWithContext($message, $context);
244 } else {
245 $messageForGettext = $message;
246 }
247
248 $translation = dgettext(
249 $domain,
250 $messageForGettext
251 );
252
253 if ($translation === $messageForGettext) {
254 $translation = dgettext(
255 $this->getDefaultDomain(),
256 $messageForGettext
257 );
258 }
259
260 if ($translation === $messageForGettext) {
261 return $message;
262 }
263
264 return $translation;
265 }
266
267 public function translatePlural(string $singular, string $plural, int $number, ?string $context = null): string
268 {
269 if ($context !== null) {
270 $singularForGettext = $this->encodeMessageWithContext($singular, $context);
271 } else {
272 $singularForGettext = $singular;
273 }
274
275
276 $translation = ngettext(
277 $singularForGettext,
278 $plural,
279 $number
280 );
281
282 if ($translation === $singularForGettext) {
283 return $number === 1 ? $singular : $plural;
284 }
285
286 return $translation;
287 }
288
289 public function translatePluralInDomain(
290 string $domain,
291 string $singular,
292 string $plural,
293 int $number,
294 ?string $context = null
295 ): string {
296 if ($context !== null) {
297 $singularForGettext = $this->encodeMessageWithContext($singular, $context);
298 } else {
299 $singularForGettext = $singular;
300 }
301
302 $translation = dngettext(
303 $domain,
304 $singularForGettext,
305 $plural,
306 $number
307 );
308
309 $isSingular = $number === 1;
310
311 if ($translation === ($isSingular ? $singularForGettext : $plural)) {
312 $translation = dngettext(
313 $this->getDefaultDomain(),
314 $singularForGettext,
315 $plural,
316 $number
317 );
318 }
319
320 if ($translation === $singularForGettext) {
321 return $isSingular ? $singular : $plural;
322 }
323
324 return $translation;
325 }
326
327 /**
328 * List available locales by traversing the translation directories from {@see addTranslationDirectory()}
329 *
330 * @return string[] Array of available locale codes
331 */
332 public function listLocales(): array
333 {
334 $locales = [];
335
336 foreach (array_unique($this->getTranslationDirectories()) as $directory) {
337 $fs = new FilesystemIterator(
338 $directory,
339 FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS
340 );
341
342 /** @var SplFileInfo $file */
343 foreach ($fs as $file) {
344 if (! $file->isDir()) {
345 continue;
346 }
347
348 $locales[] = $file->getBasename();
349 }
350 }
351
352 $locales = array_filter(array_unique($locales));
353
354 sort($locales);
355
356 return $locales;
357 }
358 }