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
	/**
	 * @var array initial property values that will be applied to objects newly created via [[createObject]].
Qiang Xue committed
78 79
	 * The array keys are class names without leading backslashes "\", and the array values are the corresponding
	 * name-value pairs for initializing the created class instances. For example,
Qiang Xue committed
80 81 82
	 *
	 * ~~~
	 * array(
Qiang Xue committed
83
	 *     'Bar' => array(
Qiang Xue committed
84 85 86
	 *         'prop1' => 'value1',
	 *         'prop2' => 'value2',
	 *     ),
Qiang Xue committed
87
	 *     'mycompany\foo\Car' => array(
Qiang Xue committed
88 89 90 91 92 93 94 95 96
	 *         'prop1' => 'value1',
	 *         'prop2' => 'value2',
	 *     ),
	 * )
	 * ~~~
	 *
	 * @see createObject
	 */
	public static $objectConfig = array();
Qiang Xue committed
97

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

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

	/**
	 * 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
114
	 * includes the class file when the class is referenced in the code the first time.
Qiang Xue committed
115
	 *
w  
Qiang Xue committed
116 117 118 119 120
	 * 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
121
	 *
w  
Qiang Xue committed
122 123
	 * 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
124
	 *
w  
Qiang Xue committed
125
	 * To import a class or a directory, one can use either path alias or class name (can be namespaced):
Qiang Xue committed
126
	 *
w  
Qiang Xue committed
127 128 129
	 *  - `@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
130
	 *
w  
Qiang Xue committed
131
	 * @param string $alias path alias or a simple class name to be imported
Qiang Xue committed
132 133 134 135
	 * @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
136
	 * @throws \yii\base\Exception if the path alias is invalid
Qiang Xue committed
137
	 */
w  
Qiang Xue committed
138
	public static function import($alias, $forceInclude = false)
Qiang Xue committed
139
	{
w  
Qiang Xue committed
140 141 142
		if (isset(self::$_imported[$alias])) {
			return self::$_imported[$alias];
		}
Qiang Xue committed
143

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

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

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

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

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

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

	/**
w  
Qiang Xue committed
181
	 * Translates a path alias into an actual path.
m  
Qiang Xue committed
182
	 *
w  
Qiang Xue committed
183
	 * The path alias can be either a root alias registered via [[setAlias]] or an
w  
Qiang Xue committed
184 185 186
	 * 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
187
	 *
w  
Qiang Xue committed
188 189
	 * 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
190
	 *
w  
Qiang Xue committed
191 192 193
	 * 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
194
	 * @see setAlias
Qiang Xue committed
195
	 */
w  
Qiang Xue committed
196
	public static function getAlias($alias)
Qiang Xue committed
197
	{
w  
Qiang Xue committed
198 199
		if (isset(self::$aliases[$alias])) {
			return self::$aliases[$alias];
Qiang Xue committed
200
		} elseif ($alias[0] !== '@') { // not an alias
w  
Qiang Xue committed
201
			return $alias;
Qiang Xue committed
202
		} elseif (($pos = strpos($alias, '/')) !== false) {
w  
Qiang Xue committed
203
			$rootAlias = substr($alias, 0, $pos);
w  
Qiang Xue committed
204 205
			if (isset(self::$aliases[$rootAlias])) {
				return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos);
Qiang Xue committed
206 207 208 209 210 211
			}
		}
		return false;
	}

	/**
w  
Qiang Xue committed
212
	 * Registers a path alias.
m  
Qiang Xue committed
213
	 *
w  
Qiang Xue committed
214 215
	 * 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
216
	 *
w  
Qiang Xue committed
217
	 * Note that this method neither checks the existence of the path nor normalizes the path.
m  
Qiang Xue committed
218 219
	 * Any trailing '/' and '\' characters in the path will be trimmed.
	 *
w  
Qiang Xue committed
220
	 * @param string $alias alias to the path. The alias must start with '@'.
m  
Qiang Xue committed
221 222 223 224 225 226
	 * @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
227
	 * @see getAlias
Qiang Xue committed
228
	 */
w  
Qiang Xue committed
229
	public static function setAlias($alias, $path)
Qiang Xue committed
230
	{
w  
Qiang Xue committed
231
		if ($path === null) {
w  
Qiang Xue committed
232
			unset(self::$aliases[$alias]);
Qiang Xue committed
233
		} elseif ($path[0] !== '@') {
w  
Qiang Xue committed
234
			self::$aliases[$alias] = rtrim($path, '\\/');
Qiang Xue committed
235
		} elseif (($p = static::getAlias($path)) !== false) {
m  
Qiang Xue committed
236
			self::$aliases[$alias] = $p;
Qiang Xue committed
237
		} else {
m  
Qiang Xue committed
238 239
			throw new \yii\base\Exception('Invalid path: ' . $path);
		}
Qiang Xue committed
240 241 242 243
	}

	/**
	 * Class autoload loader.
w  
Qiang Xue committed
244 245 246 247 248 249 250 251 252 253 254 255 256
	 * 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
257 258 259 260 261
	 * @param string $className class name
	 * @return boolean whether the class has been loaded successfully
	 */
	public static function autoload($className)
	{
w  
Qiang Xue committed
262
		if (isset(self::$classMap[$className])) {
Qiang Xue committed
263
			include(self::$classMap[$className]);
w  
Qiang Xue committed
264 265 266 267 268 269
			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
270
			$alias = '@' . str_replace('\\', '/', ltrim($className, '\\'));
w  
Qiang Xue committed
271
			if (($path = static::getAlias($alias)) !== false) {
w  
Qiang Xue committed
272 273
				include($path . '.php');
				return true;
Qiang Xue committed
274
			}
w  
Qiang Xue committed
275
			return false;
Qiang Xue committed
276
		}
w  
Qiang Xue committed
277 278 279 280 281

		// 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
282
			if (($path = static::getAlias($alias)) !== false) {
w  
Qiang Xue committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
				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
298 299
	}

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

w  
Qiang Xue committed
356 357
		if (!class_exists($class, false)) {
			$class = static::import($class, true);
w  
Qiang Xue committed
358 359
		}

Qiang Xue committed
360
		if (($n = func_num_args()) > 1) {
w  
Qiang Xue committed
361
			$args = func_get_args();
Qiang Xue committed
362 363 364 365 366 367 368 369 370 371 372
			if ($n === 2) {
				$object = new $class($args[1]);
			} elseif ($n === 3) {
				$object = new $class($args[1], $args[2]);
			} elseif ($n === 4) {
				$object = new $class($args[1], $args[2], $args[3]);
			} else {
				array_shift($args); // remove $config
				$r = new \ReflectionClass($class);
				$object = $r->newInstanceArgs($args);
			}
Qiang Xue committed
373
		} else {
Qiang Xue committed
374
			$object = new $class;
Qiang Xue committed
375 376
		}

Qiang Xue committed
377
		$class = get_class($object);
Qiang Xue committed
378

Qiang Xue committed
379 380
		if (isset(\Yii::$objectConfig[$class])) {
			$config = array_merge(\Yii::$objectConfig[$class], $config);
w  
Qiang Xue committed
381 382
		}

Qiang Xue committed
383 384
		foreach ($config as $name => $value) {
			$object->$name = $value;
w  
Qiang Xue committed
385
		}
Qiang Xue committed
386 387 388

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

		return $object;
w  
Qiang Xue committed
392 393
	}

Qiang Xue committed
394
	/**
w  
Qiang Xue committed
395 396 397 398 399
	 * 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
400
	 */
w  
Qiang Xue committed
401
	public static function trace($message, $category = 'application')
Qiang Xue committed
402
	{
w  
Qiang Xue committed
403
		if (YII_DEBUG) {
w  
Qiang Xue committed
404
			self::getLogger()->trace($message, $category);
w  
Qiang Xue committed
405
		}
Qiang Xue committed
406 407 408
	}

	/**
w  
Qiang Xue committed
409 410 411 412 413
	 * 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
414
	 */
Qiang Xue committed
415
	public static function error($message, $category = 'application')
Qiang Xue committed
416
	{
w  
Qiang Xue committed
417 418 419 420 421 422 423 424 425 426
		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
427
	public static function warning($message, $category = 'application')
w  
Qiang Xue committed
428
	{
w  
Qiang Xue committed
429
		self::getLogger()->warning($message, $category);
Qiang Xue committed
430 431 432
	}

	/**
w  
Qiang Xue committed
433 434 435 436 437 438
	 * 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
439
	public static function info($message, $category = 'application')
w  
Qiang Xue committed
440 441 442 443 444 445 446 447 448 449 450
	{
		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
451 452 453 454
	 * // some code to be profiled
	 *     \Yii::beginProfile('block2');
	 *     // some other code to be profiled
	 *     \Yii::endProfile('block2');
w  
Qiang Xue committed
455 456
	 * \Yii::endProfile('block1');
	 * ~~~
Qiang Xue committed
457 458
	 * @param string $token token for the code block
	 * @param string $category the category of this log message
Qiang Xue committed
459 460
	 * @see endProfile
	 */
Qiang Xue committed
461
	public static function beginProfile($token, $category = 'application')
Qiang Xue committed
462
	{
Qiang Xue committed
463
		self::getLogger()->beginProfile($token, $category);
Qiang Xue committed
464 465 466 467
	}

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

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

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

	/**
w  
Qiang Xue committed
501 502
	 * 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
503 504 505 506 507 508 509 510
	 */
	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.
511
	 * This method supports choice format (see {@link CChoiceFormat}),
Qiang Xue committed
512 513 514 515 516 517 518 519
	 * 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>.
520
	 * The first parameter can be a number without key.
Qiang Xue committed
521 522
	 * And in this case, the method will call {@link CChoiceFormat::format} to choose
	 * an appropriate message translation.
523
	 * You can pass parameter for {@link CChoiceFormat::format}
Qiang Xue committed
524 525 526 527 528 529 530 531
	 * 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
532
	public static function t($category, $message, $params = array(), $source = null, $language = null)
Qiang Xue committed
533
	{
w  
Qiang Xue committed
534
		if (self::$app !== null)
Qiang Xue committed
535
		{
w  
Qiang Xue committed
536
			if ($source === null)
w  
Qiang Xue committed
537 538
				$source = $category === 'yii' ? 'coreMessages' : 'messages';
			if (($source = self::$app->getComponent($source)) !== null)
w  
Qiang Xue committed
539
				$message = $source->translate($category, $message, $language);
Qiang Xue committed
540
		}
w  
Qiang Xue committed
541
		if ($params === array())
Qiang Xue committed
542
			return $message;
w  
Qiang Xue committed
543 544 545
		if (!is_array($params))
			$params = array($params);
		if (isset($params[0])) // number choice
Qiang Xue committed
546
		{
w  
Qiang Xue committed
547
			if (strpos($message, '|') !== false)
Qiang Xue committed
548
			{
w  
Qiang Xue committed
549
				if (strpos($message, '#') === false)
Qiang Xue committed
550
				{
w  
Qiang Xue committed
551
					$chunks = explode('|', $message);
w  
Qiang Xue committed
552
					$expressions = self::$app->getLocale($language)->getPluralRules();
w  
Qiang Xue committed
553
					if ($n = min(count($chunks), count($expressions)))
Qiang Xue committed
554
					{
w  
Qiang Xue committed
555 556
						for ($i = 0;$i < $n;$i++)
							$chunks[$i] = $expressions[$i] . '#' . $chunks[$i];
Qiang Xue committed
557

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