1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Core\Translator;
6:
7: use Atk4\Core\DiContainerTrait;
8: use Atk4\Core\Exception;
9: use Atk4\Core\Translator\Adapter\Generic;
10:
11: /**
12: * @phpstan-consistent-constructor
13: */
14: class Translator
15: {
16: use DiContainerTrait;
17:
18: private static ?self $instance = null;
19:
20: private ?ITranslatorAdapter $adapter = null;
21:
22: protected string $defaultDomain = 'atk';
23:
24: protected string $defaultLocale = 'en';
25:
26: private function __construct()
27: {
28: // singleton
29: }
30:
31: public function setDefaultLocale(string $locale): self
32: {
33: $this->defaultLocale = $locale;
34:
35: return $this;
36: }
37:
38: public function setDefaultDomain(string $defaultDomain): self
39: {
40: $this->defaultDomain = $defaultDomain;
41:
42: return $this;
43: }
44:
45: private function __clone()
46: {
47: // prevent cloning
48: }
49:
50: public function __sleep(): array
51: {
52: throw new Exception('Serialization is not supported');
53: }
54:
55: public static function instance(): self
56: {
57: if (self::$instance === null) {
58: self::$instance = new static();
59: }
60:
61: return self::$instance;
62: }
63:
64: public function setAdapter(ITranslatorAdapter $translator): self
65: {
66: $this->adapter = $translator;
67:
68: return $this;
69: }
70:
71: private function getAdapter(): ITranslatorAdapter
72: {
73: if ($this->adapter === null) {
74: $this->adapter = new Generic();
75: }
76:
77: return $this->adapter;
78: }
79:
80: /**
81: * Translate the given message.
82: *
83: * @param string $message The message to be translated
84: * @param array<string, mixed> $parameters Array of parameters used to translate message
85: * @param string|null $domain The domain for the message or null to use the default
86: * @param string|null $locale The locale or null to use the default
87: *
88: * @return string The translated string
89: */
90: public function _(string $message, array $parameters = [], string $domain = null, string $locale = null): string
91: {
92: return $this->getAdapter()->_($message, $parameters, $domain ?? $this->defaultDomain, $locale ?? $this->defaultLocale);
93: }
94: }
95: