Completed
Push — master ( b7a96a...376006 )
by Alexander
40:44 queued 34:50
created

I18N::init()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 10
cts 10
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 4
nop 0
crap 5
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']) && !isset($this->translations['yii*'])) {
59 535
            $this->translations['yii'] = [
60
                'class' => 'yii\i18n\PhpMessageSource',
61
                'sourceLanguage' => 'en-US',
62
                'basePath' => '@yii/messages',
63
            ];
64
        }
65
66 535
        if (!isset($this->translations['app']) && !isset($this->translations['app*'])) {
67 535
            $this->translations['app'] = [
68 535
                'class' => 'yii\i18n\PhpMessageSource',
69 535
                'sourceLanguage' => Yii::$app->sourceLanguage,
70 535
                'basePath' => '@app/messages',
71
            ];
72
        }
73 535
    }
74
75
    /**
76
     * Translates a message to the specified language.
77
     *
78
     * After translation the message will be formatted using [[MessageFormatter]] if it contains
79
     * ICU message format and `$params` are not empty.
80
     *
81
     * @param string $category the message category.
82
     * @param string $message the message to be translated.
83
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
84
     * @param string $language the language code (e.g. `en-US`, `en`).
85
     * @return string the translated and formatted message.
86
     */
87 533
    public function translate($category, $message, $params, $language)
88
    {
89 533
        $messageSource = $this->getMessageSource($category);
90 533
        $translation = $messageSource->translate($category, $message, $language);
91 533
        if ($translation === false) {
92 388
            return $this->format($message, $params, $messageSource->sourceLanguage);
93
        }
94
95 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 90 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...
96
    }
97
98
    /**
99
     * Formats a message using [[MessageFormatter]].
100
     *
101
     * @param string $message the message to be formatted.
102
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
103
     * @param string $language the language code (e.g. `en-US`, `en`).
104
     * @return string the formatted message.
105
     */
106 535
    public function format($message, $params, $language)
107
    {
108 535
        $params = (array) $params;
109 535
        if ($params === []) {
110 522
            return $message;
111
        }
112
113 183
        if (preg_match('~{\s*[\w]+\s*,~u', $message)) {
114 123
            $formatter = $this->getMessageFormatter();
115 123
            $result = $formatter->format($message, $params, $language);
116 123
            if ($result === false) {
117
                $errorMessage = $formatter->getErrorMessage();
118
                Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.", __METHOD__);
119
120
                return $message;
121
            }
122
123 123
            return $result;
124
        }
125
126 65
        $p = [];
127 65
        foreach ($params as $name => $value) {
128 65
            $p['{' . $name . '}'] = $value;
129
        }
130
131 65
        return strtr($message, $p);
132
    }
133
134
    /**
135
     * @var string|array|MessageFormatter
136
     */
137
    private $_messageFormatter;
138
139
    /**
140
     * Returns the message formatter instance.
141
     * @return MessageFormatter the message formatter to be used to format message via ICU message format.
142
     */
143 123
    public function getMessageFormatter()
144
    {
145 123
        if ($this->_messageFormatter === null) {
146 123
            $this->_messageFormatter = new MessageFormatter();
147 104
        } elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) {
148
            $this->_messageFormatter = Yii::createObject($this->_messageFormatter);
149
        }
150
151 123
        return $this->_messageFormatter;
152
    }
153
154
    /**
155
     * @param string|array|MessageFormatter $value the message formatter to be used to format message via ICU message format.
156
     * Can be given as array or string configuration that will be given to [[Yii::createObject]] to create an instance
157
     * or a [[MessageFormatter]] instance.
158
     */
159
    public function setMessageFormatter($value)
160
    {
161
        $this->_messageFormatter = $value;
162
    }
163
164
    /**
165
     * Returns the message source for the given category.
166
     * @param string $category the category name.
167
     * @return MessageSource the message source for the given category.
168
     * @throws InvalidConfigException if there is no message source available for the specified category.
169
     */
170 533
    public function getMessageSource($category)
171
    {
172 533
        if (isset($this->translations[$category])) {
173 531
            $source = $this->translations[$category];
174 531
            if ($source instanceof MessageSource) {
175 403
                return $source;
176
            }
177
178 529
            return $this->translations[$category] = Yii::createObject($source);
179
        }
180
        // try wildcard matching
181 4
        foreach ($this->translations as $pattern => $source) {
182 4
            if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
183
                if ($source instanceof MessageSource) {
184
                    return $source;
185
                }
186
187 4
                return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source);
188
            }
189
        }
190
191
        // match '*' in the last
192 4
        if (isset($this->translations['*'])) {
193 4
            $source = $this->translations['*'];
194 4
            if ($source instanceof MessageSource) {
195 4
                return $source;
196
            }
197
198 2
            return $this->translations[$category] = $this->translations['*'] = Yii::createObject($source);
199
        }
200
201
        throw new InvalidConfigException("Unable to locate message source for category '$category'.");
202
    }
203
}
204