-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathChinese.php
98 lines (83 loc) · 2.33 KB
/
Chinese.php
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace SteelyWing\Chinese;
class Chinese
{
const ZH_HANS = 'zh-Hans';
const ZH_HANT = 'zh-Hant';
const CHS = self::ZH_HANS;
const CHT = self::ZH_HANT;
public $dictPath = __DIR__ . '/dict/';
private $locale = self::ZH_HANT;
private $dict = [];
public function __construct(array $dictionaries = [self::ZH_HANS, self::ZH_HANT])
{
foreach ($dictionaries as $dict) {
$this->load($dict);
}
}
public function load($locale, $path = null)
{
if ($path === null) {
$path = $this->dictPath . $locale . '.csv';
}
$originalLocale = [
'LC_COLLATE' => setlocale(LC_COLLATE, 0),
'LC_CTYPE' => setlocale(LC_CTYPE, 0),
];
// If not set to zh_*, parsing CSV will not work properly
// setlocale(LC_ALL, 'zh_Hant');
setlocale(LC_COLLATE, 'zh_Hant');
setlocale(LC_CTYPE, 'zh_Hant');
$file = new \SplFileObject($path);
$file->setFlags(
\SplFileObject::READ_CSV |
\SplFileObject::SKIP_EMPTY |
\SplFileObject::READ_AHEAD
);
$dict = [];
$this->dict[$locale] =& $dict;
foreach ($file as $fields) {
if (count($fields) != 2) {
throw new \Exception(
sprintf("Cannot parse '%s' file (line %s)",
$file->getPathname(),
$file->key()
)
);
}
$dict[$fields[0]] = $fields[1];
}
setlocale(LC_COLLATE, $originalLocale['LC_COLLATE']);
setlocale(LC_CTYPE, $originalLocale['LC_CTYPE']);
return $this;
}
public function to($locale, $string)
{
return strtr($string, $this->dict[$locale]);
}
/**
* @param $string
* @return string
*/
public function convert($string)
{
return strtr($string, $this->dict[$this->locale]);
}
/**
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* @param string $locale
*/
public function setLocale($locale)
{
if (!isset($this->dict[$locale])) {
throw new \InvalidArgumentException("Locale not found: {$locale}");
}
$this->locale = $locale;
}
}