1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AbterPhp\Framework\I18n; |
6
|
|
|
|
7
|
|
|
class Translator implements ITranslator |
8
|
|
|
{ |
9
|
|
|
/** @var array */ |
10
|
|
|
protected $translations = []; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Translator constructor. |
14
|
|
|
* |
15
|
|
|
* @param array $translations |
16
|
|
|
*/ |
17
|
|
|
public function __construct(array $translations) |
18
|
|
|
{ |
19
|
|
|
$this->setTranslations($translations); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param array $translations |
24
|
|
|
*/ |
25
|
|
|
public function setTranslations(array $translations) |
26
|
|
|
{ |
27
|
|
|
$this->translations = $translations; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param string $key |
32
|
|
|
* @param string ...$args |
33
|
|
|
* |
34
|
|
|
* @return string |
35
|
|
|
*/ |
36
|
|
|
public function translate(string $key, string ...$args): string |
37
|
|
|
{ |
38
|
|
|
return $this->translateByArgs($key, $args); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $key |
43
|
|
|
* @param array ...$args |
44
|
|
|
* |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
|
|
public function canTranslate(string $key, ...$args): bool |
48
|
|
|
{ |
49
|
|
|
$res = $this->translateByArgs($key, $args); |
50
|
|
|
|
51
|
|
|
if (strpos($res, '{{translation ') !== 0) { |
52
|
|
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return substr($res, -2) !== '}}'; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string $key |
60
|
|
|
* @param array $args |
61
|
|
|
* |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
|
|
protected function translateByArgs(string $key, array $args = []): string |
65
|
|
|
{ |
66
|
|
|
$pathParts = explode(':', $key); |
67
|
|
|
|
68
|
|
|
$translations = &$this->translations; |
69
|
|
|
foreach ($pathParts as $pathPart) { |
70
|
|
|
if (!is_array($translations) || !array_key_exists($pathPart, $translations)) { |
71
|
|
|
return "{{translation missing: $key}}"; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$translations = &$translations[$pathPart]; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
if (!is_string($translations)) { |
78
|
|
|
return "{{translation is ambiguous: $key}}"; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
foreach ($args as $argKey => $argValue) { |
82
|
|
|
$argTranslation = $this->translateByArgs($argValue); |
83
|
|
|
|
84
|
|
|
if (substr($argTranslation, 0, 2) === '{{') { |
85
|
|
|
continue; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
$args[$argKey] = $argTranslation; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return vsprintf($translations, $args); |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|