Issues (910)

framework/i18n/GettextMessageSource.php (1 issue)

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
use yii\base\InvalidArgumentException;
12
13
/**
14
 * GettextMessageSource represents a message source that is based on GNU Gettext.
15
 *
16
 * Each GettextMessageSource instance represents the message translations
17
 * for a single domain. And each message category represents a message context
18
 * in Gettext. Translated messages are stored as either a MO or PO file,
19
 * depending on the [[useMoFile]] property value.
20
 *
21
 * All translations are saved under the [[basePath]] directory.
22
 *
23
 * Translations in one language are kept as MO or PO files under an individual
24
 * subdirectory whose name is the language ID. The file name is specified via
25
 * [[catalog]] property, which defaults to 'messages'.
26
 *
27
 * @author Qiang Xue <[email protected]>
28
 * @since 2.0
29
 */
30
class GettextMessageSource extends MessageSource
31
{
32
    const MO_FILE_EXT = '.mo';
33
    const PO_FILE_EXT = '.po';
34
35
    /**
36
     * @var string base directory of messages files
37
     */
38
    public $basePath = '@app/messages';
39
    /**
40
     * @var string sub-directory of messages files
41
     */
42
    public $catalog = 'messages';
43
    /**
44
     * @var bool whether to use generated MO files
45
     */
46
    public $useMoFile = true;
47
    /**
48
     * @var bool whether to use big-endian when reading and writing an integer
49
     */
50
    public $useBigEndian = false;
51
52
53
    /**
54
     * Loads the message translation for the specified $language and $category.
55
     * If translation for specific locale code such as `en-US` isn't found it
56
     * tries more generic `en`. When both are present, the `en-US` messages will be merged
57
     * over `en`. See [[loadFallbackMessages]] for details.
58
     * If the $language is less specific than [[sourceLanguage]], the method will try to
59
     * load the messages for [[sourceLanguage]]. For example: [[sourceLanguage]] is `en-GB`,
60
     * $language is `en`. The method will load the messages for `en` and merge them over `en-GB`.
61
     *
62
     * @param string $category the message category
63
     * @param string $language the target language
64
     * @return array the loaded messages. The keys are original messages, and the values are translated messages.
65
     * @see loadFallbackMessages
66
     * @see sourceLanguage
67
     */
68
    protected function loadMessages($category, $language)
69
    {
70
        $messageFile = $this->getMessageFilePath($language);
71
        $messages = $this->loadMessagesFromFile($messageFile, $category);
72
73
        $fallbackLanguage = substr($language, 0, 2);
74
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
75
76
        if ($fallbackLanguage !== '' && $fallbackLanguage !== $language) {
77
            $messages = $this->loadFallbackMessages($category, $fallbackLanguage, $messages, $messageFile);
78
        } elseif ($fallbackSourceLanguage !== '' && $language === $fallbackSourceLanguage) {
79
            $messages = $this->loadFallbackMessages($category, $this->sourceLanguage, $messages, $messageFile);
80
        } elseif ($messages === null) {
81
            Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__);
82
        }
83
84
        return (array) $messages;
85
    }
86
87
    /**
88
     * The method is normally called by [[loadMessages]] to load the fallback messages for the language.
89
     * Method tries to load the $category messages for the $fallbackLanguage and adds them to the $messages array.
90
     *
91
     * @param string $category the message category
92
     * @param string $fallbackLanguage the target fallback language
93
     * @param array $messages the array of previously loaded translation messages.
94
     * The keys are original messages, and the values are the translated messages.
95
     * @param string $originalMessageFile the path to the file with messages. Used to log an error message
96
     * in case when no translations were found.
97
     * @return array the loaded messages. The keys are original messages, and the values are the translated messages.
98
     * @since 2.0.7
99
     */
100
    protected function loadFallbackMessages($category, $fallbackLanguage, $messages, $originalMessageFile)
101
    {
102
        $fallbackMessageFile = $this->getMessageFilePath($fallbackLanguage);
103
        $fallbackMessages = $this->loadMessagesFromFile($fallbackMessageFile, $category);
104
105
        if (
106
            $messages === null && $fallbackMessages === null
107
            && $fallbackLanguage !== $this->sourceLanguage
108
            && strpos($this->sourceLanguage, $fallbackLanguage) !== 0
0 ignored issues
show
It seems like $this->sourceLanguage can also be of type null; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

108
            && strpos(/** @scrutinizer ignore-type */ $this->sourceLanguage, $fallbackLanguage) !== 0
Loading history...
109
        ) {
110
            Yii::error("The message file for category '$category' does not exist: $originalMessageFile "
111
                . "Fallback file does not exist as well: $fallbackMessageFile", __METHOD__);
112
        } elseif (empty($messages)) {
113
            return $fallbackMessages;
114
        } elseif (!empty($fallbackMessages)) {
115
            foreach ($fallbackMessages as $key => $value) {
116
                if (!empty($value) && empty($messages[$key])) {
117
                    $messages[$key] = $value;
118
                }
119
            }
120
        }
121
122
        return (array) $messages;
123
    }
124
125
    /**
126
     * Returns message file path for the specified language and category.
127
     *
128
     * @param string $language the target language
129
     * @return string path to message file
130
     */
131
    protected function getMessageFilePath($language)
132
    {
133
        $language = (string) $language;
134
        if ($language !== '' && !preg_match('/^[a-z0-9_-]+$/i', $language)) {
135
            throw new InvalidArgumentException(sprintf('Invalid language code: "%s".', $language));
136
        }
137
        $messageFile = Yii::getAlias($this->basePath) . '/' . $language . '/' . $this->catalog;
138
        if ($this->useMoFile) {
139
            $messageFile .= self::MO_FILE_EXT;
140
        } else {
141
            $messageFile .= self::PO_FILE_EXT;
142
        }
143
144
        return $messageFile;
145
    }
146
147
    /**
148
     * Loads the message translation for the specified language and category or returns null if file doesn't exist.
149
     *
150
     * @param string $messageFile path to message file
151
     * @param string $category the message category
152
     * @return array|null array of messages or null if file not found
153
     */
154
    protected function loadMessagesFromFile($messageFile, $category)
155
    {
156
        if (is_file($messageFile)) {
157
            if ($this->useMoFile) {
158
                $gettextFile = new GettextMoFile(['useBigEndian' => $this->useBigEndian]);
159
            } else {
160
                $gettextFile = new GettextPoFile();
161
            }
162
            $messages = $gettextFile->load($messageFile, $category);
163
            if (!is_array($messages)) {
164
                $messages = [];
165
            }
166
167
            return $messages;
168
        }
169
170
        return null;
171
    }
172
}
173