Completed
Push — 7964-i18n-fallback ( 32c424 )
by Dmitry
08:04
created

GettextMessageSource::loadMessages()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 20
rs 9.2
cc 4
eloc 13
nc 4
nop 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\i18n;
9
10
use Yii;
11
12
/**
13
 * GettextMessageSource represents a message source that is based on GNU Gettext.
14
 *
15
 * Each GettextMessageSource instance represents the message translations
16
 * for a single domain. And each message category represents a message context
17
 * in Gettext. Translated messages are stored as either a MO or PO file,
18
 * depending on the [[useMoFile]] property value.
19
 *
20
 * All translations are saved under the [[basePath]] directory.
21
 *
22
 * Translations in one language are kept as MO or PO files under an individual
23
 * subdirectory whose name is the language ID. The file name is specified via
24
 * [[catalog]] property, which defaults to 'messages'.
25
 *
26
 * @author Qiang Xue <[email protected]>
27
 * @since 2.0
28
 */
29
class GettextMessageSource extends MessageSource
30
{
31
    const MO_FILE_EXT = '.mo';
32
    const PO_FILE_EXT = '.po';
33
34
    /**
35
     * @var string
36
     */
37
    public $basePath = '@app/messages';
38
    /**
39
     * @var string
40
     */
41
    public $catalog = 'messages';
42
    /**
43
     * @var boolean
44
     */
45
    public $useMoFile = true;
46
    /**
47
     * @var boolean
48
     */
49
    public $useBigEndian = false;
50
51
52
    /**
53
     * Loads the message translation for the specified $language and $category.
54
     * If translation for specific locale code such as `en-US` isn't found it
55
     * tries more generic `en`. When both are present, the `en-US` messages will be merged
56
     * over `en`. See [[loadFallbackMessages]] for details.
57
     * If the $language is less specific than [[sourceLanguage]], the method will try to
58
     * load the messages for [[sourceLanguage]]. For example: [[sourceLanguage]] is `en-GB`,
59
     * $language is `en`. The method will load the messages for `en` and merge them over `en-GB`.
60
     *
61
     * @param string $category the message category
62
     * @param string $language the target language
63
     * @return array the loaded messages. The keys are original messages, and the values are translated messages.
64
     * @see loadFallbackMessages
65
     * @see sourceLanguage
66
     */
67
    protected function loadMessages($category, $language)
68
    {
69
        $messageFile = $this->getMessageFilePath($language);
70
        $messages = $this->loadMessagesFromFile($messageFile, $category);
71
72
        $fallbackLanguage = substr($language, 0, 2);
73
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
74
75
        if ($fallbackLanguage !== $language) {
76
            $this->loadFallbackMessages($category, $fallbackLanguage, $messages, $messageFile);
0 ignored issues
show
Bug introduced by
It seems like $messages defined by $this->loadMessagesFromF...messageFile, $category) on line 70 can also be of type null; however, yii\i18n\GettextMessageS...:loadFallbackMessages() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
77
        } elseif ($language === $fallbackSourceLanguage) {
78
            $messages = $this->loadFallbackMessages($category, $this->sourceLanguage, $messages, $messageFile);
0 ignored issues
show
Bug introduced by
It seems like $messages defined by $this->loadFallbackMessa...messages, $messageFile) on line 78 can also be of type null; however, yii\i18n\GettextMessageS...:loadFallbackMessages() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
79
        } else {
80
            if ($messages === null) {
81
                Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__);
82
            }
83
        }
84
85
        return (array) $messages;
86
    }
87
88
    /**
89
     * The method is normally called by [[loadMessages]] to load the fallback messages for the language.
90
     * Method tries to load the $category messages for the $fallbackLanguage and adds them to the $messages array.
91
     *
92
     * @param string $category the message category
93
     * @param string $fallbackLanguage the target fallback language
94
     * @param array $messages the array of previously loaded translation messages.
95
     * The keys are original messages, and the values are the translated messages.
96
     * @param string $originalMessageFile the path to the file with messages. Used to log an error message
97
     * in case when no translations were found.
98
     * @return array the loaded messages. The keys are original messages, and the values are the translated messages.
99
     * @since 2.0.7
100
     */
101
    protected function loadFallbackMessages($category, $fallbackLanguage, $messages, $originalMessageFile)
102
    {
103
        $fallbackMessageFile = $this->getMessageFilePath($fallbackLanguage);
104
        $fallbackMessages = $this->loadMessagesFromFile($fallbackMessageFile, $category);
105
106
        if ($messages === null && $fallbackMessages === null && $fallbackLanguage !== $this->sourceLanguage) {
107
            Yii::error("The message file for category '$category' does not exist: $originalMessageFile "
108
                . "Fallback file does not exist as well: $fallbackMessageFile", __METHOD__);
109
        } elseif (empty($messages)) {
110
            return $fallbackMessages;
111
        } elseif (!empty($fallbackMessages)) {
112
            foreach ($fallbackMessages as $key => $value) {
113
                if (!empty($value) && empty($messages[$key])) {
114
                    $messages[$key] = $fallbackMessages[$key];
115
                }
116
            }
117
        }
118
119
        return (array) $messages;
120
    }
121
122
    /**
123
     * Returns message file path for the specified language and category.
124
     *
125
     * @param string $language the target language
126
     * @return string path to message file
127
     */
128
    protected function getMessageFilePath($language)
129
    {
130
        $messageFile = Yii::getAlias($this->basePath) . '/' . $language . '/' . $this->catalog;
131
        if ($this->useMoFile) {
132
            $messageFile .= self::MO_FILE_EXT;
133
        } else {
134
            $messageFile .= self::PO_FILE_EXT;
135
        }
136
137
        return $messageFile;
138
    }
139
140
    /**
141
     * Loads the message translation for the specified language and category or returns null if file doesn't exist.
142
     *
143
     * @param string $messageFile path to message file
144
     * @param string $category the message category
145
     * @return array|null array of messages or null if file not found
146
     */
147
    protected function loadMessagesFromFile($messageFile, $category)
148
    {
149
        if (is_file($messageFile)) {
150
            if ($this->useMoFile) {
151
                $gettextFile = new GettextMoFile(['useBigEndian' => $this->useBigEndian]);
152
            } else {
153
                $gettextFile = new GettextPoFile();
154
            }
155
            $messages = $gettextFile->load($messageFile, $category);
156
            if (!is_array($messages)) {
157
                $messages = [];
158
            }
159
160
            return $messages;
161
        } else {
162
            return null;
163
        }
164
    }
165
}
166