I18N.php 6.01 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 11

namespace yii\i18n;

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

Qiang Xue committed
14 15 16
/**
 * I18N provides features related with internationalization (I18N) and localization (L10N).
 *
17 18 19
 * I18N is configured as an application component in [[yii\base\Application]] by default.
 * You can access that instance via `Yii::$app->i18n`.
 *
20 21 22 23
 * @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
24 25 26
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
27 28
class I18N extends Component
{
29 30 31 32 33
	/**
	 * @var array list of [[MessageSource]] configurations or objects. The array keys are message
	 * categories, and the array values are the corresponding [[MessageSource]] objects or the configurations
	 * for creating the [[MessageSource]] objects. The message categories 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'.
Qiang Xue committed
34 35 36 37 38 39 40 41 42 43
	 *
	 * 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.
44 45 46
	 */
	public $translations;

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

Qiang Xue committed
69 70
	/**
	 * Translates a message to the specified language.
71
	 *
Carsten Brandt committed
72
	 * After translation the message will be formatted using [[MessageFormatter]] if it contains
Carsten Brandt committed
73
	 * ICU message format and `$params` are not empty.
74
	 *
75
	 * @param string $category the message category.
Qiang Xue committed
76 77
	 * @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.
Qiang Xue committed
78
	 * @param string $language the language code (e.g. `en_US`, `en`).
79
	 * @return string the translated and formatted message.
Qiang Xue committed
80
	 */
Qiang Xue committed
81
	public function translate($category, $message, $params, $language)
Qiang Xue committed
82
	{
83
		$message = $this->getMessageSource($category)->translate($category, $message, $language);
Qiang Xue committed
84
		return $this->format($message, $params, $language);
85 86 87
	}

	/**
88
	 * Formats a message using [[MessageFormatter]].
89 90 91 92 93 94 95 96 97 98 99 100 101 102
	 *
	 * @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.
	 * @param string $language the language code (e.g. `en_US`, `en`).
	 * @return string the formatted message.
	 */
	public function format($message, $params, $language)
	{
		$params = (array)$params;
		if ($params === []) {
			return $message;
		}

		if (preg_match('~{\s*[\d\w]+\s*,~u', $message)) {
103 104
			$formatter = $this->getMessageFormatter();
			$result = $formatter->format($message, $params, $language);
105 106
			if ($result === false) {
				$errorMessage = $formatter->getErrorMessage();
Qiang Xue committed
107
				Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.");
108 109 110 111 112 113 114
				return $message;
			} else {
				return $result;
			}
		}

		$p = [];
115 116 117 118
		foreach($params as $name => $value) {
			$p['{' . $name . '}'] = $value;
		}
		return strtr($message, $p);
Qiang Xue committed
119 120
	}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
	/**
	 * @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
150 151 152 153 154 155
	/**
	 * 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
156
	public function getMessageSource($category)
Qiang Xue committed
157
	{
158 159
		if (isset($this->translations[$category])) {
			$source = $this->translations[$category];
Qiang Xue committed
160
		} else {
161 162
			// try wildcard matching
			foreach ($this->translations as $pattern => $config) {
Qiang Xue committed
163
				if ($pattern === '*' || substr($pattern, -1) === '*' && strpos($category, rtrim($pattern, '*')) === 0) {
164 165 166 167
					$source = $config;
					break;
				}
			}
Qiang Xue committed
168
		}
169 170
		if (isset($source)) {
			return $source instanceof MessageSource ? $source : Yii::createObject($source);
Qiang Xue committed
171
		} else {
172
			throw new InvalidConfigException("Unable to locate message source for category '$category'.");
Qiang Xue committed
173 174 175
		}
	}
}