I18N.php 5.87 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 20
 * @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
21 22 23
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
24 25
class I18N extends Component
{
26 27 28 29 30
	/**
	 * @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
31 32 33 34 35 36 37 38 39 40
	 *
	 * 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.
41 42 43
	 */
	public $translations;

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

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

	/**
85
	 * Formats a message using [[MessageFormatter]].
86 87 88 89 90 91 92 93 94 95 96 97 98 99
	 *
	 * @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)) {
100 101
			$formatter = $this->getMessageFormatter();
			$result = $formatter->format($message, $params, $language);
102 103
			if ($result === false) {
				$errorMessage = $formatter->getErrorMessage();
Qiang Xue committed
104
				Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.");
105 106 107 108 109 110 111
				return $message;
			} else {
				return $result;
			}
		}

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

118 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
	/**
	 * @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
147 148 149 150 151 152
	/**
	 * 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
153
	public function getMessageSource($category)
Qiang Xue committed
154
	{
155 156
		if (isset($this->translations[$category])) {
			$source = $this->translations[$category];
Qiang Xue committed
157
		} else {
158 159
			// try wildcard matching
			foreach ($this->translations as $pattern => $config) {
Qiang Xue committed
160
				if ($pattern === '*' || substr($pattern, -1) === '*' && strpos($category, rtrim($pattern, '*')) === 0) {
161 162 163 164
					$source = $config;
					break;
				}
			}
Qiang Xue committed
165
		}
166 167
		if (isset($source)) {
			return $source instanceof MessageSource ? $source : Yii::createObject($source);
Qiang Xue committed
168
		} else {
169
			throw new InvalidConfigException("Unable to locate message source for category '$category'.");
Qiang Xue committed
170 171 172
		}
	}
}