-
-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathGenericTranslator.php
More file actions
52 lines (43 loc) · 1.47 KB
/
GenericTranslator.php
File metadata and controls
52 lines (43 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
namespace Tempest\Intl;
use Tempest\EventBus\EventBus;
use Tempest\Intl\Catalog\Catalog;
use Tempest\Intl\IntlConfig;
use Tempest\Intl\Locale;
use Tempest\Intl\MessageFormat\Formatter\MessageFormatter;
final readonly class GenericTranslator implements Translator
{
public function __construct(
private(set) IntlConfig $config,
private(set) Catalog $catalog,
private MessageFormatter $formatter,
private ?EventBus $eventBus = null,
) {}
public function translateForLocale(Locale $locale, string $key, mixed ...$arguments): string
{
if (! $this->catalog->has($locale, $key)) {
$this->eventBus?->dispatch(new TranslationMiss(
locale: $locale,
key: $key,
));
}
$message = $this->catalog->get($locale, $key) ?? $this->catalog->get($this->config->fallbackLocale, $key);
if ($message === null) {
return $key;
}
try {
return $this->formatter->format(mb_trim($message), ...$arguments);
} catch (\Throwable $exception) {
$this->eventBus?->dispatch(new TranslationFailure(
locale: $locale,
key: $key,
exception: $exception,
));
return $key;
}
}
public function translate(string $key, mixed ...$arguments): string
{
return $this->translateForLocale($this->config->currentLocale, $key, ...$arguments);
}
}