I18N.php 6.86 KB
Newer Older
Qiang Xue committed
1
<?php
Qiang Xue committed
2 3 4 5 6
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
Qiang Xue committed
7 8 9 10

namespace yii\i18n;

use Yii;
11
use yii\base\Arrayable;
Qiang Xue committed
12
use yii\base\Component;
13
use yii\base\InvalidConfigException;
Qiang Xue committed
14

Qiang Xue committed
15 16 17
/**
 * I18N provides features related with internationalization (I18N) and localization (L10N).
 *
18
 * I18N is configured as an application component in [[\yii\base\Application]] by default.
19 20
 * You can access that instance via `Yii::$app->i18n`.
 *
21 22 23 24
 * @property MessageFormatter $messageFormatter The message formatter to be used to format message via ICU
 * message format. Note that the type of this property differs in getter and setter. See
 * [[getMessageFormatter()]] and [[setMessageFormatter()]] for details.
 *
Qiang Xue committed
25 26 27
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
28 29
class I18N extends Component
{
30 31
	/**
	 * @var array list of [[MessageSource]] configurations or objects. The array keys are message
32 33 34 35 36 37 38
	 * category patterns, and the array values are the corresponding [[MessageSource]] objects or the configurations
	 * for creating the [[MessageSource]] objects.
	 *
	 * The message category patterns can contain the wildcard '*' at the end to match multiple categories with the same prefix.
	 * For example, 'app\*' matches both 'app\cat1' and 'app\cat2'.
	 *
	 * The '*' category pattern will match all categories that do not match any other category patterns.
Qiang Xue committed
39 40 41 42 43 44 45 46 47 48
	 *
	 * This property may be modified on the fly by extensions who want to have their own message sources
	 * registered under their own namespaces.
	 *
	 * The category "yii" and "app" are always defined. The former refers to the messages used in the Yii core
	 * framework code, while the latter refers to the default message category for custom application code.
	 * By default, both of these categories use [[PhpMessageSource]] and the corresponding message files are
	 * stored under "@yii/messages" and "@app/messages", respectively.
	 *
	 * You may override the configuration of both categories.
49 50 51
	 */
	public $translations;

Qiang Xue committed
52 53 54
	/**
	 * Initializes the component by configuring the default message categories.
	 */
55 56
	public function init()
	{
Qiang Xue committed
57
		parent::init();
58
		if (!isset($this->translations['yii'])) {
Alexander Makarov committed
59
			$this->translations['yii'] = [
60
				'class' => 'yii\i18n\PhpMessageSource',
Alexander Makarov committed
61
				'sourceLanguage' => 'en',
62
				'basePath' => '@yii/messages',
Alexander Makarov committed
63
			];
64 65
		}
		if (!isset($this->translations['app'])) {
Alexander Makarov committed
66
			$this->translations['app'] = [
67
				'class' => 'yii\i18n\PhpMessageSource',
Alexander Makarov committed
68
				'sourceLanguage' => 'en',
69
				'basePath' => '@app/messages',
Alexander Makarov committed
70
			];
71 72 73
		}
	}

Qiang Xue committed
74 75
	/**
	 * Translates a message to the specified language.
76
	 *
Carsten Brandt committed
77
	 * After translation the message will be formatted using [[MessageFormatter]] if it contains
Carsten Brandt committed
78
	 * ICU message format and `$params` are not empty.
79
	 *
80
	 * @param string $category the message category.
Qiang Xue committed
81 82
	 * @param string $message the message to be translated.
	 * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
83
	 * @param string $language the language code (e.g. `en-US`, `en`).
84
	 * @return string the translated and formatted message.
Qiang Xue committed
85
	 */
Qiang Xue committed
86
	public function translate($category, $message, $params, $language)
Qiang Xue committed
87
	{
88 89 90 91 92 93 94
		$messageSource = $this->getMessageSource($category);
		$translation = $messageSource->translate($category, $message, $language);
		if ($translation === false) {
			return $this->format($message, $params, $messageSource->sourceLanguage);
		} else {
			return $this->format($translation, $params, $language);
		}
95 96 97
	}

	/**
98
	 * Formats a message using [[MessageFormatter]].
99 100 101
	 *
	 * @param string $message the message to be formatted.
	 * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
102
	 * @param string $language the language code (e.g. `en-US`, `en`).
103 104 105 106
	 * @return string the formatted message.
	 */
	public function format($message, $params, $language)
	{
107 108 109 110 111
		if ($params instanceof Arrayable) {
			$params = $params->toArray();
		} else {
			$params = (array)$params;
		}
112 113 114 115 116
		if ($params === []) {
			return $message;
		}

		if (preg_match('~{\s*[\d\w]+\s*,~u', $message)) {
117 118
			$formatter = $this->getMessageFormatter();
			$result = $formatter->format($message, $params, $language);
119 120
			if ($result === false) {
				$errorMessage = $formatter->getErrorMessage();
Qiang Xue committed
121
				Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.");
122 123 124 125 126 127 128
				return $message;
			} else {
				return $result;
			}
		}

		$p = [];
129 130 131 132
		foreach($params as $name => $value) {
			$p['{' . $name . '}'] = $value;
		}
		return strtr($message, $p);
Qiang Xue committed
133 134
	}

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
	/**
	 * @var string|array|MessageFormatter
	 */
	private $_messageFormatter;

	/**
	 * Returns the message formatter instance.
	 * @return MessageFormatter the message formatter to be used to format message via ICU message format.
	 */
	public function getMessageFormatter()
	{
		if ($this->_messageFormatter === null) {
			$this->_messageFormatter = new MessageFormatter();
		} elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) {
			$this->_messageFormatter = Yii::createObject($this->_messageFormatter);
		}
		return $this->_messageFormatter;
	}

	/**
	 * @param string|array|MessageFormatter $value the message formatter to be used to format message via ICU message format.
	 * Can be given as array or string configuration that will be given to [[Yii::createObject]] to create an instance
	 * or a [[MessageFormatter]] instance.
	 */
	public function setMessageFormatter($value)
	{
		$this->_messageFormatter = $value;
	}

Qiang Xue committed
164 165 166 167 168 169
	/**
	 * Returns the message source for the given category.
	 * @param string $category the category name.
	 * @return MessageSource the message source for the given category.
	 * @throws InvalidConfigException if there is no message source available for the specified category.
	 */
Qiang Xue committed
170
	public function getMessageSource($category)
Qiang Xue committed
171
	{
172 173
		if (isset($this->translations[$category])) {
			$source = $this->translations[$category];
174 175 176 177 178
			if ($source instanceof MessageSource) {
				return $source;
			} else {
				return $this->translations[$category] = Yii::createObject($source);
			}
Qiang Xue committed
179
		} else {
180
			// try wildcard matching
181 182 183 184
			foreach ($this->translations as $pattern => $source) {
				if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
					if ($source instanceof MessageSource) {
						return $source;
185
					} else {
186
						return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source);
187
					}
188 189
				}
			}
190 191 192 193 194 195 196 197 198
			// match '*' in the last
			if (isset($this->translations['*'])) {
				$source = $this->translations['*'];
				if ($source instanceof MessageSource) {
					return $source;
				} else {
					return $this->translations[$category] = $this->translations['*'] = Yii::createObject($source);
				}
			}
Qiang Xue committed
199
		}
200 201

		throw new InvalidConfigException("Unable to locate message source for category '$category'.");
Qiang Xue committed
202 203
	}
}