1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace RemiSan\Intl; |
4
|
|
|
|
5
|
|
|
class ResourceTranslator |
6
|
|
|
{ |
7
|
|
|
/** @var string */ |
8
|
|
|
private $resourcesDirectory; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @var \ResourceBundle[] |
12
|
|
|
*/ |
13
|
|
|
private $resourceBundles; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Constructor. |
17
|
|
|
* |
18
|
|
|
* @param $resourcesDirectory |
19
|
|
|
*/ |
20
|
12 |
|
public function __construct($resourcesDirectory) |
21
|
|
|
{ |
22
|
12 |
|
$this->resourcesDirectory = $resourcesDirectory; |
23
|
12 |
|
$this->resourceBundles = []; |
24
|
12 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Translate the $resource |
28
|
|
|
* |
29
|
|
|
* @param string $locale |
30
|
|
|
* @param TranslatableResource $resource |
31
|
|
|
* |
32
|
|
|
* @throws \IntlException |
33
|
|
|
* @return string |
34
|
|
|
*/ |
35
|
12 |
|
public function translate($locale, TranslatableResource $resource) |
36
|
|
|
{ |
37
|
12 |
|
$canonicalLocale = \Locale::canonicalize($locale); |
38
|
12 |
|
$messageFormatter = new \MessageFormatter( |
39
|
8 |
|
$canonicalLocale, |
40
|
12 |
|
$this->retrievePattern($canonicalLocale, $resource->getKey()) |
41
|
4 |
|
); |
42
|
|
|
|
43
|
6 |
|
return $messageFormatter->format($resource->getParameters()); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Retrieve the pattern from the resource bundle |
48
|
|
|
* |
49
|
|
|
* @param string $locale |
50
|
|
|
* @param string $key |
51
|
|
|
* |
52
|
|
|
* @throws \IntlException |
53
|
|
|
* @return mixed |
54
|
|
|
*/ |
55
|
12 |
|
private function retrievePattern($locale, $key) |
56
|
|
|
{ |
57
|
12 |
|
$resBundle = $this->getResourceBundle($locale); |
58
|
|
|
|
59
|
9 |
|
$pattern = $resBundle->get($key); |
60
|
|
|
|
61
|
9 |
|
if ($pattern === null) { |
62
|
3 |
|
throw new \IntlException($resBundle->getErrorMessage(), $resBundle->getErrorCode()); |
63
|
|
|
} |
64
|
|
|
|
65
|
6 |
|
return $pattern; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param string $locale |
70
|
|
|
* |
71
|
|
|
* @throws \IntlException |
72
|
|
|
* @return \ResourceBundle |
73
|
|
|
*/ |
74
|
12 |
|
private function getResourceBundle($locale) |
75
|
|
|
{ |
76
|
12 |
|
if (!isset($this->resourceBundles[$locale])) { |
77
|
12 |
|
$resourceBundle = \ResourceBundle::create($locale, $this->resourcesDirectory, true); |
78
|
|
|
|
79
|
12 |
|
if ($resourceBundle === null) { |
80
|
3 |
|
throw new \IntlException('Could not create resource bundle'); |
81
|
|
|
} |
82
|
|
|
|
83
|
9 |
|
$this->resourceBundles[$locale] = $resourceBundle; |
84
|
6 |
|
} |
85
|
|
|
|
86
|
9 |
|
return $this->resourceBundles[$locale]; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|