Completed
Push — 11429-message-source ( f7ff15 )
by Dmitry
10:08
created

GettextMessageSource::loadFallbackMessages()   C

Complexity

Conditions 10
Paths 4

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 24
ccs 0
cts 22
cp 0
rs 5.2164
cc 10
eloc 16
nc 4
nop 4
crap 110

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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