Completed
Push — master ( c9de61...744b87 )
by Alexander
41:24 queued 38:21
created

I18N::init()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 13
cts 13
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 18
nc 10
nop 0
crap 7
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
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
14
/**
15
 * I18N provides features related with internationalization (I18N) and localization (L10N).
16
 *
17
 * I18N is configured as an application component in [[\yii\base\Application]] by default.
18
 * You can access that instance via `Yii::$app->i18n`.
19
 *
20
 * @property MessageFormatter $messageFormatter The message formatter to be used to format message via ICU
21
 * message format. Note that the type of this property differs in getter and setter. See
22
 * [[getMessageFormatter()]] and [[setMessageFormatter()]] for details.
23
 *
24
 * @author Qiang Xue <[email protected]>
25
 * @since 2.0
26
 */
27
class I18N extends Component
28
{
29
    /**
30
     * @var array list of [[MessageSource]] configurations or objects. The array keys are message
31
     * category patterns, and the array values are the corresponding [[MessageSource]] objects or the configurations
32
     * for creating the [[MessageSource]] objects.
33
     *
34
     * The message category patterns can contain the wildcard `*` at the end to match multiple categories with the same prefix.
35
     * For example, `app/*` matches both `app/cat1` and `app/cat2`.
36
     *
37
     * The `*` category pattern will match all categories that do not match any other category patterns.
38
     *
39
     * This property may be modified on the fly by extensions who want to have their own message sources
40
     * registered under their own namespaces.
41
     *
42
     * The category `yii` and `app` are always defined. The former refers to the messages used in the Yii core
43
     * framework code, while the latter refers to the default message category for custom application code.
44
     * By default, both of these categories use [[PhpMessageSource]] and the corresponding message files are
45
     * stored under `@yii/messages` and `@app/messages`, respectively.
46
     *
47
     * You may override the configuration of both categories.
48
     */
49
    public $translations;
50
51
52
    /**
53
     * Initializes the component by configuring the default message categories.
54
     */
55 535
    public function init()
56
    {
57 535
        parent::init();
58 535
        if (!isset($this->translations['yii*'])) {
59 535
            if (!isset($this->translations['yii'])) {
60 535
                $this->translations['yii'] = [
61
                    'class' => 'yii\i18n\PhpMessageSource',
62
                    'sourceLanguage' => 'en-US',
63
                    'basePath' => '@yii/messages',
64
                ];
65
            }
66 535
            if (!isset($this->translations['yii-*']) && !isset($this->translations['yii-rest'])) {
67 535
                $this->translations['yii-rest'] = [
68
                    'class' => 'yii\i18n\PhpMessageSource',
69
                    'sourceLanguage' => 'en-US',
70
                    'basePath' => '@yii/messages',
71
                ];
72
            }
73
        }
74
75 535
        if (!isset($this->translations['app']) && !isset($this->translations['app*'])) {
76 535
            $this->translations['app'] = [
77 535
                'class' => 'yii\i18n\PhpMessageSource',
78 535
                'sourceLanguage' => Yii::$app->sourceLanguage,
79 535
                'basePath' => '@app/messages',
80
            ];
81
        }
82 535
    }
83
84
    /**
85
     * Translates a message to the specified language.
86
     *
87
     * After translation the message will be formatted using [[MessageFormatter]] if it contains
88
     * ICU message format and `$params` are not empty.
89
     *
90
     * @param string $category the message category.
91
     * @param string $message the message to be translated.
92
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
93
     * @param string $language the language code (e.g. `en-US`, `en`).
94
     * @return string the translated and formatted message.
95
     */
96 533
    public function translate($category, $message, $params, $language)
97
    {
98 533
        $messageSource = $this->getMessageSource($category);
99 533
        $translation = $messageSource->translate($category, $message, $language);
100 533
        if ($translation === false) {
101 388
            return $this->format($message, $params, $messageSource->sourceLanguage);
102
        }
103
104 165
        return $this->format($translation, $params, $language);
0 ignored issues
show
Bug introduced by
It seems like $translation defined by $messageSource->translat...y, $message, $language) on line 99 can also be of type boolean; however, yii\i18n\I18N::format() does only seem to accept string, 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...
105
    }
106
107
    /**
108
     * Formats a message using [[MessageFormatter]].
109
     *
110
     * @param string $message the message to be formatted.
111
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
112
     * @param string $language the language code (e.g. `en-US`, `en`).
113
     * @return string the formatted message.
114
     */
115 535
    public function format($message, $params, $language)
116
    {
117 535
        $params = (array) $params;
118 535
        if ($params === []) {
119 522
            return $message;
120
        }
121
122 183
        if (preg_match('~{\s*[\w]+\s*,~u', $message)) {
123 123
            $formatter = $this->getMessageFormatter();
124 123
            $result = $formatter->format($message, $params, $language);
125 123
            if ($result === false) {
126
                $errorMessage = $formatter->getErrorMessage();
127
                Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.", __METHOD__);
128
129
                return $message;
130
            }
131
132 123
            return $result;
133
        }
134
135 65
        $p = [];
136 65
        foreach ($params as $name => $value) {
137 65
            $p['{' . $name . '}'] = $value;
138
        }
139
140 65
        return strtr($message, $p);
141
    }
142
143
    /**
144
     * @var string|array|MessageFormatter
145
     */
146
    private $_messageFormatter;
147
148
    /**
149
     * Returns the message formatter instance.
150
     * @return MessageFormatter the message formatter to be used to format message via ICU message format.
151
     */
152 123
    public function getMessageFormatter()
153
    {
154 123
        if ($this->_messageFormatter === null) {
155 123
            $this->_messageFormatter = new MessageFormatter();
156 104
        } elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) {
157
            $this->_messageFormatter = Yii::createObject($this->_messageFormatter);
158
        }
159
160 123
        return $this->_messageFormatter;
161
    }
162
163
    /**
164
     * @param string|array|MessageFormatter $value the message formatter to be used to format message via ICU message format.
165
     * Can be given as array or string configuration that will be given to [[Yii::createObject]] to create an instance
166
     * or a [[MessageFormatter]] instance.
167
     */
168
    public function setMessageFormatter($value)
169
    {
170
        $this->_messageFormatter = $value;
171
    }
172
173
    /**
174
     * Returns the message source for the given category.
175
     * @param string $category the category name.
176
     * @return MessageSource the message source for the given category.
177
     * @throws InvalidConfigException if there is no message source available for the specified category.
178
     */
179 533
    public function getMessageSource($category)
180
    {
181 533
        if (isset($this->translations[$category])) {
182 531
            $source = $this->translations[$category];
183 531
            if ($source instanceof MessageSource) {
184 403
                return $source;
185
            }
186
187 529
            return $this->translations[$category] = Yii::createObject($source);
188
        }
189
        // try wildcard matching
190 4
        foreach ($this->translations as $pattern => $source) {
191 4
            if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
192
                if ($source instanceof MessageSource) {
193
                    return $source;
194
                }
195
196 4
                return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source);
197
            }
198
        }
199
200
        // match '*' in the last
201 4
        if (isset($this->translations['*'])) {
202 4
            $source = $this->translations['*'];
203 4
            if ($source instanceof MessageSource) {
204 4
                return $source;
205
            }
206
207 2
            return $this->translations[$category] = $this->translations['*'] = Yii::createObject($source);
208
        }
209
210
        throw new InvalidConfigException("Unable to locate message source for category '$category'.");
211
    }
212
}
213