Issues (836)

framework/i18n/I18N.php (1 issue)

Labels
Severity
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\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 774
    public function init()
56
    {
57 774
        parent::init();
58 774
        if (!isset($this->translations['yii']) && !isset($this->translations['yii*'])) {
59 774
            $this->translations['yii'] = [
60 774
                'class' => 'yii\i18n\PhpMessageSource',
61 774
                'sourceLanguage' => 'en-US',
62 774
                'basePath' => '@yii/messages',
63 774
            ];
64
        }
65
66 774
        if (!isset($this->translations['app']) && !isset($this->translations['app*'])) {
67 774
            $this->translations['app'] = [
68 774
                'class' => 'yii\i18n\PhpMessageSource',
69 774
                'sourceLanguage' => Yii::$app->sourceLanguage,
70 774
                'basePath' => '@app/messages',
71 774
            ];
72
        }
73
    }
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 772
    public function translate($category, $message, $params, $language)
88
    {
89 772
        $messageSource = $this->getMessageSource($category);
90 772
        $translation = $messageSource->translate($category, $message, $language);
91 772
        if ($translation === false) {
92 621
            return $this->format($message, $params, $messageSource->sourceLanguage);
93
        }
94
95 167
        return $this->format($translation, $params, $language);
0 ignored issues
show
It seems like $translation can also be of type true; however, parameter $message of yii\i18n\I18N::format() 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

95
        return $this->format(/** @scrutinizer ignore-type */ $translation, $params, $language);
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 774
    public function format($message, $params, $language)
107
    {
108 774
        $params = (array) $params;
109 774
        if ($params === []) {
110 765
            return $message;
111
        }
112
113 203
        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 86
        $p = [];
127 86
        foreach ($params as $name => $value) {
128 86
            $p['{' . $name . '}'] = $value;
129
        }
130
131 86
        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 103
        } 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 772
    public function getMessageSource($category)
171
    {
172 772
        if (isset($this->translations[$category])) {
173 771
            $source = $this->translations[$category];
174 771
            if ($source instanceof MessageSource) {
175 618
                return $source;
176
            }
177
178 770
            return $this->translations[$category] = Yii::createObject($source);
179
        }
180
        // try wildcard matching
181 2
        foreach ($this->translations as $pattern => $source) {
182 2
            if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
183
                if ($source instanceof MessageSource) {
184
                    return $source;
185
                }
186
187
                return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source);
188
            }
189
        }
190
191
        // match '*' in the last
192 2
        if (isset($this->translations['*'])) {
193 2
            $source = $this->translations['*'];
194 2
            if ($source instanceof MessageSource) {
195 2
                return $source;
196
            }
197
198 1
            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