YiiBase.php 19 KB
Newer Older
Qiang Xue committed
1
<?php
w  
Qiang Xue committed
2 3 4 5 6 7 8
/**
 * YiiBase class file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008-2012 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
Qiang Xue committed
9 10

/**
w  
Qiang Xue committed
11
 * Gets the application start timestamp.
Qiang Xue committed
12
 */
w  
Qiang Xue committed
13
defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME', microtime(true));
Qiang Xue committed
14 15 16
/**
 * This constant defines whether the application should be in debug mode or not. Defaults to false.
 */
w  
Qiang Xue committed
17
defined('YII_DEBUG') or define('YII_DEBUG', false);
Qiang Xue committed
18 19 20 21 22
/**
 * This constant defines how much call stack information (file name and line number) should be logged by Yii::trace().
 * Defaults to 0, meaning no backtrace information. If it is greater than 0,
 * at most that number of call stacks will be logged. Note, only user application call stacks are considered.
 */
w  
Qiang Xue committed
23
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 0);
Qiang Xue committed
24 25 26
/**
 * This constant defines whether exception handling should be enabled. Defaults to true.
 */
w  
Qiang Xue committed
27
defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER', true);
Qiang Xue committed
28 29 30
/**
 * This constant defines whether error handling should be enabled. Defaults to true.
 */
w  
Qiang Xue committed
31
defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true);
Qiang Xue committed
32
/**
w  
Qiang Xue committed
33
 * This constant defines the framework installation directory.
Qiang Xue committed
34
 */
w  
Qiang Xue committed
35 36
defined('YII_PATH') or define('YII_PATH', __DIR__);

Qiang Xue committed
37
/**
w  
Qiang Xue committed
38
 * YiiBase is the core helper class for the Yii framework.
Qiang Xue committed
39
 *
w  
Qiang Xue committed
40
 * Do not use YiiBase directly. Instead, use its child class [[Yii]] where
Qiang Xue committed
41 42 43
 * you can customize methods of YiiBase.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
44
 * @since 2.0
Qiang Xue committed
45 46 47 48 49
 */
class YiiBase
{
	/**
	 * @var array class map used by the Yii autoloading mechanism.
w  
Qiang Xue committed
50 51
	 * The array keys are the class names, and the array values are the corresponding class file paths.
	 * This property mainly affects how [[autoload]] works.
Qiang Xue committed
52 53
	 * @see import
	 * @see autoload
w  
Qiang Xue committed
54 55 56 57 58 59
	 */
	public static $classMap = array();
	/**
	 * @var array list of directories where Yii will search for new classes to be included.
	 * The first directory in the array will be searched first, and so on.
	 * This property mainly affects how [[autoload]] works.
Qiang Xue committed
60 61
	 * @see import
	 * @see autoload
w  
Qiang Xue committed
62 63 64 65
	 */
	public static $classPath = array();
	/**
	 * @var yii\base\Application the application instance
Qiang Xue committed
66
	 */
Qiang Xue committed
67
	public static $application;
w  
Qiang Xue committed
68 69
	/**
	 * @var array registered path aliases
Qiang Xue committed
70 71
	 * @see getAlias
	 * @see setAlias
w  
Qiang Xue committed
72 73
	 */
	public static $aliases = array(
w  
Qiang Xue committed
74
		'@yii' => __DIR__,
w  
Qiang Xue committed
75
	);
Qiang Xue committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	/**
	 * @var array initial property values that will be applied to objects newly created via [[createObject]].
	 * The array keys are fully qualified namespaced class names, and the array values are the corresponding
	 * name-value pairs for initializing the created class instances. Make sure the class names do not have
	 * the leading backslashes. For example,
	 *
	 * ~~~
	 * array(
	 *     'mycompany\foo\Bar' => array(
	 *         'prop1' => 'value1',
	 *         'prop2' => 'value2',
	 *     ),
	 *     'mycompany\foo\Car' => array(
	 *         'prop1' => 'value1',
	 *         'prop2' => 'value2',
	 *     ),
	 * )
	 * ~~~
	 *
	 * @see createObject
	 */
	public static $objectConfig = array();
Qiang Xue committed
98

w  
Qiang Xue committed
99 100
	private static $_imported = array();	// alias => class name or directory
	private static $_logger;
Qiang Xue committed
101 102 103 104 105 106

	/**
	 * @return string the version of Yii framework
	 */
	public static function getVersion()
	{
w  
Qiang Xue committed
107
		return '2.0-dev';
Qiang Xue committed
108 109 110 111 112 113 114
	}

	/**
	 * Imports a class or a directory.
	 *
	 * Importing a class is like including the corresponding class file.
	 * The main difference is that importing a class is much lighter because it only
w  
Qiang Xue committed
115
	 * includes the class file when the class is referenced in the code the first time.
Qiang Xue committed
116
	 *
w  
Qiang Xue committed
117 118 119 120 121
	 * Importing a directory will add the directory to the front of the [[classPath]] array.
	 * When [[autoload]] is loading an unknown class, it will search in the directories
	 * specified in [[classPath]] to find the corresponding class file to include.
	 * For this reason, if multiple directories are imported, the directories imported later
	 * will take precedence in class file searching.
Qiang Xue committed
122
	 *
w  
Qiang Xue committed
123 124
	 * The same class or directory can be imported multiple times. Only the first importing
	 * will count. Importing a directory does not import any of its subdirectories.
Qiang Xue committed
125
	 *
w  
Qiang Xue committed
126
	 * To import a class or a directory, one can use either path alias or class name (can be namespaced):
Qiang Xue committed
127
	 *
w  
Qiang Xue committed
128 129 130
	 *  - `@app/components/GoogleMap`: importing the `GoogleMap` class with a path alias;
	 *  - `GoogleMap`: importing the `GoogleMap` class with a class name;
	 *  - `@app/components/*`: importing the whole `components` directory with a path alias.
Qiang Xue committed
131
	 *
w  
Qiang Xue committed
132
	 * @param string $alias path alias or a simple class name to be imported
Qiang Xue committed
133 134 135 136
	 * @param boolean $forceInclude whether to include the class file immediately. If false, the class file
	 * will be included only when the class is being used. This parameter is used only when
	 * the path alias refers to a class.
	 * @return string the class name or the directory that this alias refers to
w  
Qiang Xue committed
137
	 * @throws \yii\base\Exception if the path alias is invalid
Qiang Xue committed
138
	 */
w  
Qiang Xue committed
139
	public static function import($alias, $forceInclude = false)
Qiang Xue committed
140
	{
w  
Qiang Xue committed
141 142 143
		if (isset(self::$_imported[$alias])) {
			return self::$_imported[$alias];
		}
Qiang Xue committed
144

w  
Qiang Xue committed
145 146
		if (class_exists($alias, false) || interface_exists($alias, false)) {
			return self::$_imported[$alias] = $alias;
Qiang Xue committed
147 148
		}

w  
Qiang Xue committed
149
		if ($alias[0] !== '@') { // a simple class name
w  
Qiang Xue committed
150
			if ($forceInclude && static::autoload($alias)) {
w  
Qiang Xue committed
151 152
				self::$_imported[$alias] = $alias;
			}
Qiang Xue committed
153 154 155
			return $alias;
		}

w  
Qiang Xue committed
156
		$className = basename($alias);
w  
Qiang Xue committed
157
		$isClass = $className !== '*';
Qiang Xue committed
158

w  
Qiang Xue committed
159 160 161
		if ($isClass && (class_exists($className, false) || interface_exists($className, false))) {
			return self::$_imported[$alias] = $className;
		}
Qiang Xue committed
162

w  
Qiang Xue committed
163
		if (($path = static::getAlias(dirname($alias))) === false) {
w  
Qiang Xue committed
164 165
			throw new \yii\base\Exception('Invalid path alias: ' . $alias);
		}
Qiang Xue committed
166

w  
Qiang Xue committed
167 168 169 170
		if ($isClass) {
			if ($forceInclude) {
				require($path . "/$className.php");
				self::$_imported[$alias] = $className;
Qiang Xue committed
171
			} else {
w  
Qiang Xue committed
172 173 174
				self::$classMap[$className] = $path . "/$className.php";
			}
			return $className;
Qiang Xue committed
175
		} else { // a directory
w  
Qiang Xue committed
176 177
			array_unshift(self::$classPath, $path);
			return self::$_imported[$alias] = $path;
Qiang Xue committed
178 179 180 181
		}
	}

	/**
w  
Qiang Xue committed
182
	 * Translates a path alias into an actual path.
m  
Qiang Xue committed
183
	 *
w  
Qiang Xue committed
184
	 * The path alias can be either a root alias registered via [[setAlias]] or an
w  
Qiang Xue committed
185 186 187
	 * alias starting with a root alias (e.g. `@yii/base/Component.php`).
	 * In the latter case, the root alias will be replaced by the corresponding registered path
	 * and the remaining part will be appended to it.
m  
Qiang Xue committed
188
	 *
w  
Qiang Xue committed
189 190
	 * In case the given parameter is not an alias (i.e., not starting with '@'),
	 * it will be returned back without change.
w  
Qiang Xue committed
191
	 *
w  
Qiang Xue committed
192 193 194
	 * Note, this method does not ensure the existence of the resulting path.
	 * @param string $alias alias
	 * @return mixed path corresponding to the alias, false if the root alias is not previously registered.
w  
Qiang Xue committed
195
	 * @see setAlias
Qiang Xue committed
196
	 */
w  
Qiang Xue committed
197
	public static function getAlias($alias)
Qiang Xue committed
198
	{
w  
Qiang Xue committed
199 200
		if (isset(self::$aliases[$alias])) {
			return self::$aliases[$alias];
Qiang Xue committed
201
		} elseif ($alias[0] !== '@') { // not an alias
w  
Qiang Xue committed
202
			return $alias;
Qiang Xue committed
203
		} elseif (($pos = strpos($alias, '/')) !== false) {
w  
Qiang Xue committed
204
			$rootAlias = substr($alias, 0, $pos);
w  
Qiang Xue committed
205 206
			if (isset(self::$aliases[$rootAlias])) {
				return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos);
Qiang Xue committed
207 208 209 210 211 212
			}
		}
		return false;
	}

	/**
w  
Qiang Xue committed
213
	 * Registers a path alias.
m  
Qiang Xue committed
214
	 *
w  
Qiang Xue committed
215 216
	 * A path alias is a short name representing a path (a file path, a URL, etc.)
	 * A path alias must start with '@' (e.g. '@yii').
m  
Qiang Xue committed
217
	 *
w  
Qiang Xue committed
218
	 * Note that this method neither checks the existence of the path nor normalizes the path.
m  
Qiang Xue committed
219 220
	 * Any trailing '/' and '\' characters in the path will be trimmed.
	 *
w  
Qiang Xue committed
221
	 * @param string $alias alias to the path. The alias must start with '@'.
m  
Qiang Xue committed
222 223 224 225 226 227
	 * @param string $path the path corresponding to the alias. This can be
	 *
	 * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
	 * - a URL (e.g. `http://www.yiiframework.com`)
	 * - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the
	 *   actual path first by calling [[getAlias]].
w  
Qiang Xue committed
228
	 * @see getAlias
Qiang Xue committed
229
	 */
w  
Qiang Xue committed
230
	public static function setAlias($alias, $path)
Qiang Xue committed
231
	{
w  
Qiang Xue committed
232
		if ($path === null) {
w  
Qiang Xue committed
233
			unset(self::$aliases[$alias]);
Qiang Xue committed
234
		} elseif ($path[0] !== '@') {
w  
Qiang Xue committed
235
			self::$aliases[$alias] = rtrim($path, '\\/');
Qiang Xue committed
236
		} elseif (($p = static::getAlias($path)) !== false) {
m  
Qiang Xue committed
237
			self::$aliases[$alias] = $p;
Qiang Xue committed
238
		} else {
m  
Qiang Xue committed
239 240
			throw new \yii\base\Exception('Invalid path: ' . $path);
		}
Qiang Xue committed
241 242 243 244
	}

	/**
	 * Class autoload loader.
w  
Qiang Xue committed
245 246 247 248 249 250 251 252 253 254 255 256 257
	 * This method is invoked automatically when the execution encounters an unknown class.
	 * The method will attempt to include the class file as follows:
	 *
	 * 1. Search in [[classMap]];
	 * 2. If the class is namespaced (e.g. `yii\base\Component`), it will attempt
	 *    to include the file associated with the corresponding path alias
	 *    (e.g. `@yii/base/Component.php`);
	 * 3. If the class is named in PEAR style (e.g. `PHPUnit_Framework_TestCase`),
	 *    it will attempt to include the file associated with the corresponding path alias
	 *    (e.g. `@PHPUnit/Framework/TestCase.php`);
	 * 4. Search in [[classPath]];
	 * 5. Return false so that other autoloaders have chance to include the class file.
	 *
Qiang Xue committed
258 259 260 261 262
	 * @param string $className class name
	 * @return boolean whether the class has been loaded successfully
	 */
	public static function autoload($className)
	{
w  
Qiang Xue committed
263
		if (isset(self::$classMap[$className])) {
Qiang Xue committed
264
			include(self::$classMap[$className]);
w  
Qiang Xue committed
265 266 267 268 269 270
			return true;
		}

		// namespaced class, e.g. yii\base\Component
		if (strpos($className, '\\') !== false) {
			// convert namespace to path alias, e.g. yii\base\Component to @yii/base/Component
w  
Qiang Xue committed
271
			$alias = '@' . str_replace('\\', '/', ltrim($className, '\\'));
w  
Qiang Xue committed
272
			if (($path = static::getAlias($alias)) !== false) {
w  
Qiang Xue committed
273 274
				include($path . '.php');
				return true;
Qiang Xue committed
275
			}
w  
Qiang Xue committed
276
			return false;
Qiang Xue committed
277
		}
w  
Qiang Xue committed
278 279 280 281 282

		// PEAR-styled class, e.g. PHPUnit_Framework_TestCase
		if (($pos = strpos($className, '_')) !== false) {
			// convert class name to path alias, e.g. PHPUnit_Framework_TestCase to @PHPUnit/Framework/TestCase
			$alias = '@' . str_replace('_', '/', $className);
w  
Qiang Xue committed
283
			if (($path = static::getAlias($alias)) !== false) {
w  
Qiang Xue committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
				include($path . '.php');
				return true;
			}
		}

		// search in include paths
		foreach (self::$classPath as $path) {
			$classFile = $path . DIRECTORY_SEPARATOR . $className . '.php';
			if (is_file($classFile)) {
				include($classFile);
				return true;
			}
		}

		return false;
Qiang Xue committed
299 300
	}

w  
Qiang Xue committed
301
	/**
Qiang Xue committed
302
	 * Creates a new object using the given configuration.
w  
Qiang Xue committed
303
	 *
Qiang Xue committed
304 305 306
	 * The configuration can be either a string or an array.
	 * If a string, it is treated as the *object type*; if an array,
	 * it must contain a `class` element specifying the *object type*, and
w  
Qiang Xue committed
307 308 309
	 * the rest of the name-value pairs in the array will be used to initialize
	 * the corresponding object properties.
	 *
Qiang Xue committed
310
	 * The object type can be either a class name or the [[getAlias|alias]] of
w  
Qiang Xue committed
311
	 * the class. For example,
w  
Qiang Xue committed
312
	 *
Qiang Xue committed
313 314 315 316 317 318 319 320 321 322 323 324 325
	 * - `\app\components\GoogleMap`: namespaced class
	 * - `@app/components/GoogleMap`: an alias
	 *
	 * This method does the following steps to create an object:
	 *
	 * - create the object using the PHP `new` operator;
	 * - if [[objectConfig]] contains the configuration for the object class,
	 *   initialize the object properties with that configuration;
	 * - initialize the object properties using the configuration passed to this method;
	 * - call the `init` method of the object if it implements the [[yii\base\Initable]] interface.
	 *
	 * Below are some usage examples:
	 *
w  
Qiang Xue committed
326
	 * ~~~
Qiang Xue committed
327 328 329
	 * $object = \Yii::createObject('@app/components/GoogleMap');
	 * $object = \Yii::createObject(array(
	 *     'class' => '\app\components\GoogleMap',
w  
Qiang Xue committed
330 331 332 333
	 *     'apiKey' => 'xyz',
	 * ));
	 * ~~~
	 *
w  
Qiang Xue committed
334 335 336
	 * Any additional parameters passed to this method will be
	 * passed to the constructor of the object being created.
	 *
w  
Qiang Xue committed
337 338
	 * @param mixed $config the configuration. It can be either a string or an array.
	 * @return mixed the created object
w  
Qiang Xue committed
339
	 * @throws \yii\base\Exception if the configuration is invalid.
w  
Qiang Xue committed
340
	 */
Qiang Xue committed
341
	public static function createObject($config)
w  
Qiang Xue committed
342 343
	{
		if (is_string($config)) {
w  
Qiang Xue committed
344
			$class = $config;
w  
Qiang Xue committed
345
			$config = array();
Qiang Xue committed
346
		} elseif (isset($config['class'])) {
w  
Qiang Xue committed
347
			$class = $config['class'];
w  
Qiang Xue committed
348
			unset($config['class']);
Qiang Xue committed
349
		} else {
w  
Qiang Xue committed
350 351 352
			throw new \yii\base\Exception('Object configuration must be an array containing a "class" element.');
		}

w  
Qiang Xue committed
353 354
		if (!class_exists($class, false)) {
			$class = static::import($class, true);
w  
Qiang Xue committed
355 356
		}

Qiang Xue committed
357
		if (($n = func_num_args()-1) > 0) {
w  
Qiang Xue committed
358
			$args = func_get_args();
Qiang Xue committed
359
			array_shift($args); // remove $config
w  
Qiang Xue committed
360
		}
Qiang Xue committed
361 362

		if ($n === 0) {
w  
Qiang Xue committed
363
			$object = new $class;
Qiang Xue committed
364 365 366 367 368 369 370 371 372 373 374 375 376 377
		} elseif ($n === 1) {
			$object = new $class($args[0]);
		} elseif ($n === 2) {
			$object = new $class($args[0], $args[1]);
		} elseif ($n === 3) {
			$object = new $class($args[0], $args[1], $args[2]);
		} else {
			$r = new \ReflectionClass($class);
			$object = $r->newInstanceArgs($args);
		}

		$c = get_class($object);
		if (isset(\Yii::$objectConfig[$c])) {
			$config = isset($config) ? array_merge(\Yii::$objectConfig[$c], $config) : \Yii::$objectConfig[$c];
w  
Qiang Xue committed
378 379
		}

Qiang Xue committed
380 381 382 383
		if (!empty($config)) {
			foreach ($config as $name => $value) {
				$object->$name = $value;
			}
w  
Qiang Xue committed
384
		}
Qiang Xue committed
385 386 387

		if ($object instanceof \yii\base\Initable) {
			$object->init();
w  
Qiang Xue committed
388
		}
Qiang Xue committed
389 390

		return $object;
w  
Qiang Xue committed
391 392
	}

Qiang Xue committed
393
	/**
w  
Qiang Xue committed
394 395 396 397 398
	 * Logs a trace message.
	 * Trace messages are logged mainly for development purpose to see
	 * the execution work flow of some code.
	 * @param string $message the message to be logged.
	 * @param string $category the category of the message.
Qiang Xue committed
399
	 */
w  
Qiang Xue committed
400
	public static function trace($message, $category = 'application')
Qiang Xue committed
401
	{
w  
Qiang Xue committed
402
		if (YII_DEBUG) {
w  
Qiang Xue committed
403
			self::getLogger()->trace($message, $category);
w  
Qiang Xue committed
404
		}
Qiang Xue committed
405 406 407
	}

	/**
w  
Qiang Xue committed
408 409 410 411 412
	 * Logs an error message.
	 * An error message is typically logged when an unrecoverable error occurs
	 * during the execution of an application.
	 * @param string $message the message to be logged.
	 * @param string $category the category of the message.
Qiang Xue committed
413
	 */
Qiang Xue committed
414
	public static function error($message, $category = 'application')
Qiang Xue committed
415
	{
w  
Qiang Xue committed
416 417 418 419 420 421 422 423 424 425
		self::getLogger()->error($message, $category);
	}

	/**
	 * Logs a warning message.
	 * A warning message is typically logged when an error occurs while the execution
	 * can still continue.
	 * @param string $message the message to be logged.
	 * @param string $category the category of the message.
	 */
Qiang Xue committed
426
	public static function warning($message, $category = 'application')
w  
Qiang Xue committed
427
	{
w  
Qiang Xue committed
428
		self::getLogger()->warning($message, $category);
Qiang Xue committed
429 430 431
	}

	/**
w  
Qiang Xue committed
432 433 434 435 436 437
	 * Logs an informative message.
	 * An informative message is typically logged by an application to keep record of
	 * something important (e.g. an administrator logs in).
	 * @param string $message the message to be logged.
	 * @param string $category the category of the message.
	 */
Qiang Xue committed
438
	public static function info($message, $category = 'application')
w  
Qiang Xue committed
439 440 441 442 443 444 445 446 447 448 449
	{
		self::getLogger()->info($message, $category);
	}

	/**
	 * Marks the beginning of a code block for profiling.
	 * This has to be matched with a call to [[endProfile]] with the same category name.
	 * The begin- and end- calls must also be properly nested. For example,
	 *
	 * ~~~
	 * \Yii::beginProfile('block1');
Qiang Xue committed
450 451 452 453
	 * // some code to be profiled
	 *     \Yii::beginProfile('block2');
	 *     // some other code to be profiled
	 *     \Yii::endProfile('block2');
w  
Qiang Xue committed
454 455
	 * \Yii::endProfile('block1');
	 * ~~~
Qiang Xue committed
456 457
	 * @param string $token token for the code block
	 * @param string $category the category of this log message
Qiang Xue committed
458 459
	 * @see endProfile
	 */
Qiang Xue committed
460
	public static function beginProfile($token, $category = 'application')
Qiang Xue committed
461
	{
Qiang Xue committed
462
		self::getLogger()->beginProfile($token, $category);
Qiang Xue committed
463 464 465 466
	}

	/**
	 * Marks the end of a code block for profiling.
w  
Qiang Xue committed
467
	 * This has to be matched with a previous call to [[beginProfile]] with the same category name.
Qiang Xue committed
468 469
	 * @param string $token token for the code block
	 * @param string $category the category of this log message
Qiang Xue committed
470 471
	 * @see beginProfile
	 */
Qiang Xue committed
472
	public static function endProfile($token, $category = 'application')
Qiang Xue committed
473
	{
Qiang Xue committed
474
		self::getLogger()->endProfile($token, $category);
Qiang Xue committed
475 476 477
	}

	/**
w  
Qiang Xue committed
478 479
	 * Returns the message logger object.
	 * @return \yii\logging\Logger message logger
Qiang Xue committed
480 481 482
	 */
	public static function getLogger()
	{
w  
Qiang Xue committed
483
		if (self::$_logger !== null) {
Qiang Xue committed
484
			return self::$_logger;
Qiang Xue committed
485
		} else {
w  
Qiang Xue committed
486 487
			return self::$_logger = new \yii\logging\Logger;
		}
w  
Qiang Xue committed
488 489 490 491
	}

	/**
	 * Sets the logger object.
w  
Qiang Xue committed
492
	 * @param \yii\logging\Logger $logger the logger object.
w  
Qiang Xue committed
493 494 495 496
	 */
	public static function setLogger($logger)
	{
		self::$_logger = $logger;
Qiang Xue committed
497 498 499
	}

	/**
w  
Qiang Xue committed
500 501
	 * Returns an HTML hyperlink that can be displayed on your Web page showing Powered by Yii" information.
	 * @return string an HTML hyperlink that can be displayed on your Web page showing Powered by Yii" information
Qiang Xue committed
502 503 504 505 506 507 508 509
	 */
	public static function powered()
	{
		return 'Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>.';
	}

	/**
	 * Translates a message to the specified language.
510
	 * This method supports choice format (see {@link CChoiceFormat}),
Qiang Xue committed
511 512 513 514 515 516 517 518
	 * i.e., the message returned will be chosen from a few candidates according to the given
	 * number value. This feature is mainly used to solve plural format issue in case
	 * a message has different plural forms in some languages.
	 * @param string $category message category. Please use only word letters. Note, category 'yii' is
	 * reserved for Yii framework core code use. See {@link CPhpMessageSource} for
	 * more interpretation about message category.
	 * @param string $message the original message
	 * @param array $params parameters to be applied to the message using <code>strtr</code>.
519
	 * The first parameter can be a number without key.
Qiang Xue committed
520 521
	 * And in this case, the method will call {@link CChoiceFormat::format} to choose
	 * an appropriate message translation.
522
	 * You can pass parameter for {@link CChoiceFormat::format}
Qiang Xue committed
523 524 525 526 527 528 529 530
	 * or plural forms format without wrapping it with array.
	 * @param string $source which message source application component to use.
	 * Defaults to null, meaning using 'coreMessages' for messages belonging to
	 * the 'yii' category and using 'messages' for the rest messages.
	 * @param string $language the target language. If null (default), the {@link CApplication::getLanguage application language} will be used.
	 * @return string the translated message
	 * @see CMessageSource
	 */
w  
Qiang Xue committed
531
	public static function t($category, $message, $params = array(), $source = null, $language = null)
Qiang Xue committed
532
	{
w  
Qiang Xue committed
533
		if (self::$app !== null)
Qiang Xue committed
534
		{
w  
Qiang Xue committed
535
			if ($source === null)
w  
Qiang Xue committed
536 537
				$source = $category === 'yii' ? 'coreMessages' : 'messages';
			if (($source = self::$app->getComponent($source)) !== null)
w  
Qiang Xue committed
538
				$message = $source->translate($category, $message, $language);
Qiang Xue committed
539
		}
w  
Qiang Xue committed
540
		if ($params === array())
Qiang Xue committed
541
			return $message;
w  
Qiang Xue committed
542 543 544
		if (!is_array($params))
			$params = array($params);
		if (isset($params[0])) // number choice
Qiang Xue committed
545
		{
w  
Qiang Xue committed
546
			if (strpos($message, '|') !== false)
Qiang Xue committed
547
			{
w  
Qiang Xue committed
548
				if (strpos($message, '#') === false)
Qiang Xue committed
549
				{
w  
Qiang Xue committed
550
					$chunks = explode('|', $message);
w  
Qiang Xue committed
551
					$expressions = self::$app->getLocale($language)->getPluralRules();
w  
Qiang Xue committed
552
					if ($n = min(count($chunks), count($expressions)))
Qiang Xue committed
553
					{
w  
Qiang Xue committed
554 555
						for ($i = 0;$i < $n;$i++)
							$chunks[$i] = $expressions[$i] . '#' . $chunks[$i];
Qiang Xue committed
556

w  
Qiang Xue committed
557
						$message = implode('|', $chunks);
Qiang Xue committed
558 559
					}
				}
w  
Qiang Xue committed
560
				$message = CChoiceFormat::format($message, $params[0]);
Qiang Xue committed
561
			}
w  
Qiang Xue committed
562 563
			if (!isset($params['{n}']))
				$params['{n}'] = $params[0];
Qiang Xue committed
564 565
			unset($params[0]);
		}
w  
Qiang Xue committed
566
		return $params !== array() ? strtr($message, $params) : $message;
Qiang Xue committed
567 568
	}
}