-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpo2js.php
113 lines (104 loc) · 2.98 KB
/
po2js.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* translate mo file to json
* @author Anakeen
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
*/
$c = new Po2js($argv[1]);
print $c->po2json();
/**
* Convert a PO file to json string
*/
Class Po2js
{
protected $pofile = "";
protected $entries = array();
protected $encoding = 'utf-8';
/**
* Construct the object
*
* @param string $pofile path to the po file
* @throws Exception
*/
public function __construct($pofile)
{
if (file_exists($pofile)) {
$this->pofile = $pofile;
} else {
throw new Exception("PO file ($pofile) doesn't exist.");
}
}
/**
* Convert the current PO file to a json string
*
* JSON contains an object where key are po key and content po translation
* if there is no translation return an empty string
*
* @return string
*/
public function po2json()
{
$this->po2array();
if (!empty($this->entries)) {
$js = json_encode($this->entries);
if ($this->encoding === "iso") {
$js = utf8_encode($js);
}
return $js;
} else {
return "";
}
}
/**
* Extract PO entries an store them
*
* @throws Exception
*/
protected function po2array()
{
if (file_exists($this->pofile)) {
$pocontent = file_get_contents($this->pofile);
if ($pocontent !== false) {
$pocontent .= "\n\n";
preg_match_all('/^(msgctxt (?P<msgctxt>".*?))?msgid (?P<msgid>".*?)msgstr (?P<msgstr>".*?")\n\n/ms',
$pocontent, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$this->memoEntry($m['msgid'], $m['msgstr'], $m['msgctxt']);
}
} else {
throw new Exception("PO file ({$this->pofile}) is not readable.");
}
} else {
throw new Exception("PO file ({$this->pofile}) doesn't exist.");
}
}
/**
* Clean a key and a translation and add them to $this->entries
* @param $key
* @param $text
*/
protected function memoEntry($key, $text, $ctxt='')
{
$tkey = explode("\n", $key);
$ttext = explode("\n", $text);
$tctxt = explode("\n", $ctxt);
$key = trim(implode("\n", array_map('Po2js::trimquote', $tkey)));
$text = trim(implode("\n", array_map('Po2js::trimquote', $ttext)));
$ctxt = trim(implode("\n", array_map('Po2js::trimquote', $tctxt)));
if ($key && $text) {
if ($ctxt) {
$this->entries["_msgctxt_"][$ctxt][$key] = $text;
} else {
$this->entries[$key] = $text;
}
} else if ($key == "") {
if (stristr($text, "charset=ISO-8859") !== false) {
$this->encoding = 'iso';
}
}
}
protected static function trimquote($s)
{
return trim($s, '"');
}
}