3
* @link https://www.yiiframework.com/
4
* @copyright Copyright (c) 2008 Yii Software LLC
5
* @license https://www.yiiframework.com/license/
13
* GettextPoFile represents a PO Gettext message file.
15
* @author Qiang Xue <qiang.xue@gmail.com>
18
class GettextPoFile extends GettextFile
21
* Loads messages from a PO file.
22
* @param string $filePath file path
23
* @param string $context message context
24
* @return array message translations. Array keys are source messages and array values are translated messages:
25
* source message => translated message.
27
public function load($filePath, $context)
29
$pattern = '/(msgctxt\s+"(.*?(?<!\\\\))")?\s+' // context
30
. 'msgid\s+((?:".*(?<!\\\\)"\s*)+)\s+' // message ID, i.e. original string
31
. 'msgstr\s+((?:".*(?<!\\\\)"\s*)+)/'; // translated string
32
$content = file_get_contents($filePath);
34
$matchCount = preg_match_all($pattern, $content, $matches);
37
for ($i = 0; $i < $matchCount; ++$i) {
38
if ($matches[2][$i] === $context) {
39
$id = $this->decode($matches[3][$i]);
40
$message = $this->decode($matches[4][$i]);
41
$messages[$id] = $message;
49
* Saves messages to a PO file.
50
* @param string $filePath file path
51
* @param array $messages message translations. Array keys are source messages and array values are
52
* translated messages: source message => translated message. Note if the message has a context,
53
* the message ID must be prefixed with the context with chr(4) as the separator.
55
public function save($filePath, $messages)
57
$language = str_replace('-', '_', basename(dirname($filePath)));
61
'"Project-Id-Version: \n"',
62
'"POT-Creation-Date: \n"',
63
'"PO-Revision-Date: \n"',
64
'"Last-Translator: \n"',
65
'"Language-Team: \n"',
66
'"Language: ' . $language . '\n"',
67
'"MIME-Version: 1.0\n"',
68
'"Content-Type: text/plain; charset=' . Yii::$app->charset . '\n"',
69
'"Content-Transfer-Encoding: 8bit\n"',
71
$content = implode("\n", $headers) . "\n\n";
72
foreach ($messages as $id => $message) {
73
$separatorPosition = strpos($id, chr(4));
74
if ($separatorPosition !== false) {
75
$content .= 'msgctxt "' . substr($id, 0, $separatorPosition) . "\"\n";
76
$id = substr($id, $separatorPosition + 1);
78
$content .= 'msgid "' . $this->encode($id) . "\"\n";
79
$content .= 'msgstr "' . $this->encode($message) . "\"\n\n";
81
file_put_contents($filePath, $content);
85
* Encodes special characters in a message.
86
* @param string $string message to be encoded
87
* @return string the encoded message
89
protected function encode($string)
92
['"', "\n", "\t", "\r"],
93
['\\"', '\\n', '\\t', '\\r'],
99
* Decodes special characters in a message.
100
* @param string $string message to be decoded
101
* @return string the decoded message
103
protected function decode($string)
105
$string = preg_replace(
106
['/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'],
107
['', "\n", "\r", "\t", '"'],
111
return substr(rtrim($string), 1, -1);