yii2

Форк
1
/
GettextPoFile.php 
113 строк · 3.7 Кб
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7

8
namespace yii\i18n;
9

10
use Yii;
11

12
/**
13
 * GettextPoFile represents a PO Gettext message file.
14
 *
15
 * @author Qiang Xue <qiang.xue@gmail.com>
16
 * @since 2.0
17
 */
18
class GettextPoFile extends GettextFile
19
{
20
    /**
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.
26
     */
27
    public function load($filePath, $context)
28
    {
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);
33
        $matches = [];
34
        $matchCount = preg_match_all($pattern, $content, $matches);
35

36
        $messages = [];
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;
42
            }
43
        }
44

45
        return $messages;
46
    }
47

48
    /**
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.
54
     */
55
    public function save($filePath, $messages)
56
    {
57
        $language = str_replace('-', '_', basename(dirname($filePath)));
58
        $headers = [
59
            'msgid ""',
60
            'msgstr ""',
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"',
70
        ];
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);
77
            }
78
            $content .= 'msgid "' . $this->encode($id) . "\"\n";
79
            $content .= 'msgstr "' . $this->encode($message) . "\"\n\n";
80
        }
81
        file_put_contents($filePath, $content);
82
    }
83

84
    /**
85
     * Encodes special characters in a message.
86
     * @param string $string message to be encoded
87
     * @return string the encoded message
88
     */
89
    protected function encode($string)
90
    {
91
        return str_replace(
92
            ['"', "\n", "\t", "\r"],
93
            ['\\"', '\\n', '\\t', '\\r'],
94
            $string
95
        );
96
    }
97

98
    /**
99
     * Decodes special characters in a message.
100
     * @param string $string message to be decoded
101
     * @return string the decoded message
102
     */
103
    protected function decode($string)
104
    {
105
        $string = preg_replace(
106
            ['/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'],
107
            ['', "\n", "\r", "\t", '"'],
108
            $string
109
        );
110

111
        return substr(rtrim($string), 1, -1);
112
    }
113
}
114

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.