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

Qiang Xue committed
10
use yii\base\Exception;
Qiang Xue committed
11
use yii\logging\Logger;
Qiang Xue committed
12
use yii\base\InvalidCallException;
Qiang Xue committed
13
use yii\base\InvalidConfigException;
Qiang Xue committed
14

Qiang Xue committed
15
/**
w  
Qiang Xue committed
16
 * Gets the application start timestamp.
Qiang Xue committed
17
 */
w  
Qiang Xue committed
18
defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME', microtime(true));
Qiang Xue committed
19 20 21
/**
 * This constant defines whether the application should be in debug mode or not. Defaults to false.
 */
w  
Qiang Xue committed
22
defined('YII_DEBUG') or define('YII_DEBUG', false);
Qiang Xue committed
23 24 25 26 27
/**
 * 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
28
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 0);
Qiang Xue committed
29
/**
w  
Qiang Xue committed
30
 * This constant defines the framework installation directory.
Qiang Xue committed
31
 */
w  
Qiang Xue committed
32 33
defined('YII_PATH') or define('YII_PATH', __DIR__);

Qiang Xue committed
34
/**
w  
Qiang Xue committed
35
 * YiiBase is the core helper class for the Yii framework.
Qiang Xue committed
36
 *
w  
Qiang Xue committed
37
 * Do not use YiiBase directly. Instead, use its child class [[Yii]] where
Qiang Xue committed
38 39 40
 * you can customize methods of YiiBase.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
41
 * @since 2.0
Qiang Xue committed
42 43 44 45 46
 */
class YiiBase
{
	/**
	 * @var array class map used by the Yii autoloading mechanism.
w  
Qiang Xue committed
47 48
	 * 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
49 50
	 * @see import
	 * @see autoload
w  
Qiang Xue committed
51 52 53 54 55 56
	 */
	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
57 58
	 * @see import
	 * @see autoload
w  
Qiang Xue committed
59 60 61 62
	 */
	public static $classPath = array();
	/**
	 * @var yii\base\Application the application instance
Qiang Xue committed
63
	 */
Qiang Xue committed
64
	public static $application;
w  
Qiang Xue committed
65 66
	/**
	 * @var array registered path aliases
Qiang Xue committed
67 68
	 * @see getAlias
	 * @see setAlias
w  
Qiang Xue committed
69 70
	 */
	public static $aliases = array(
w  
Qiang Xue committed
71
		'@yii' => __DIR__,
w  
Qiang Xue committed
72
	);
Qiang Xue committed
73 74
	/**
	 * @var array initial property values that will be applied to objects newly created via [[createObject]].
Qiang Xue committed
75 76
	 * 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
77 78 79
	 *
	 * ~~~
	 * array(
Qiang Xue committed
80
	 *     'Bar' => array(
Qiang Xue committed
81 82 83
	 *         'prop1' => 'value1',
	 *         'prop2' => 'value2',
	 *     ),
Qiang Xue committed
84
	 *     'mycompany\foo\Car' => array(
Qiang Xue committed
85 86 87 88 89 90 91 92 93
	 *         'prop1' => 'value1',
	 *         'prop2' => 'value2',
	 *     ),
	 * )
	 * ~~~
	 *
	 * @see createObject
	 */
	public static $objectConfig = array();
Qiang Xue committed
94

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

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

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

Qiang Xue committed
142 143 144 145 146
		if ($alias[0] !== '@') {
			// a simple class name
			if (class_exists($alias, false) || interface_exists($alias, false)) {
				return self::$_imported[$alias] = $alias;
			}
w  
Qiang Xue committed
147
			if ($forceInclude && static::autoload($alias)) {
w  
Qiang Xue committed
148 149
				self::$_imported[$alias] = $alias;
			}
Qiang Xue committed
150 151 152
			return $alias;
		}

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

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

w  
Qiang Xue committed
160
		if (($path = static::getAlias(dirname($alias))) === false) {
Qiang Xue committed
161
			throw new Exception('Invalid path alias: ' . $alias);
w  
Qiang Xue committed
162
		}
Qiang Xue committed
163

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

	/**
w  
Qiang Xue committed
180
	 * Translates a path alias into an actual path.
m  
Qiang Xue committed
181
	 *
w  
Qiang Xue committed
182
	 * The path alias can be either a root alias registered via [[setAlias]] or an
w  
Qiang Xue committed
183 184 185
	 * 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
186
	 *
w  
Qiang Xue committed
187 188
	 * 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
189
	 *
w  
Qiang Xue committed
190 191
	 * Note, this method does not ensure the existence of the resulting path.
	 * @param string $alias alias
Qiang Xue committed
192 193 194
	 * @param boolean $throwException whether to throw exception if the alias is invalid.
	 * @return string|boolean path corresponding to the alias, false if the root alias is not previously registered.
	 * @throws Exception if the alias is invalid and $throwException is true.
w  
Qiang Xue committed
195
	 * @see setAlias
Qiang Xue committed
196
	 */
Qiang Xue committed
197
	public static function getAlias($alias, $throwException = false)
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 === '' || $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
			}
		}
Qiang Xue committed
209 210 211 212 213
		if ($throwException) {
			throw new Exception("Invalid path alias: $alias");
		} else {
			return false;
		}
Qiang Xue committed
214 215 216
	}

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

	/**
	 * Class autoload loader.
w  
Qiang Xue committed
250 251 252 253 254 255 256 257 258 259 260 261 262
	 * 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
263 264 265 266 267
	 * @param string $className class name
	 * @return boolean whether the class has been loaded successfully
	 */
	public static function autoload($className)
	{
w  
Qiang Xue committed
268
		if (isset(self::$classMap[$className])) {
Qiang Xue committed
269
			include(self::$classMap[$className]);
w  
Qiang Xue committed
270 271 272 273
			return true;
		}

		if (strpos($className, '\\') !== false) {
Qiang Xue committed
274
			// namespaced class, e.g. yii\base\Component
w  
Qiang Xue committed
275
			// convert namespace to path alias, e.g. yii\base\Component to @yii/base/Component
w  
Qiang Xue committed
276
			$alias = '@' . str_replace('\\', '/', ltrim($className, '\\'));
w  
Qiang Xue committed
277
			if (($path = static::getAlias($alias)) !== false) {
Qiang Xue committed
278
				$classFile = $path . '.php';
Qiang Xue committed
279
			}
Qiang Xue committed
280 281
		} elseif (($pos = strpos($className, '_')) !== false) {
			// PEAR-styled class, e.g. PHPUnit_Framework_TestCase
w  
Qiang Xue committed
282 283
			// convert class name to path alias, e.g. PHPUnit_Framework_TestCase to @PHPUnit/Framework/TestCase
			$alias = '@' . str_replace('_', '/', $className);
w  
Qiang Xue committed
284
			if (($path = static::getAlias($alias)) !== false) {
Qiang Xue committed
285
				$classFile = $path . '.php';
w  
Qiang Xue committed
286 287 288
			}
		}

Qiang Xue committed
289 290 291 292 293 294 295 296 297 298 299 300 301
		if (!isset($classFile)) {
			// search in include paths
			foreach (self::$classPath as $path) {
				$path .= DIRECTORY_SEPARATOR . $className . '.php';
				if (is_file($path)) {
					$classFile = $path;
					$alias = $className;
				}
			}
		}

		if (isset($classFile, $alias)) {
			if (!YII_DEBUG || basename(realpath($classFile)) === basename($alias) . '.php') {
w  
Qiang Xue committed
302 303
				include($classFile);
				return true;
Qiang Xue committed
304
			} else {
Qiang Xue committed
305
				throw new Exception("Class name '$className' does not match the class file '" . realpath($classFile) . "'. Have you checked their case sensitivity?");
w  
Qiang Xue committed
306 307 308 309
			}
		}

		return false;
Qiang Xue committed
310 311
	}

w  
Qiang Xue committed
312
	/**
Qiang Xue committed
313
	 * Creates a new object using the given configuration.
w  
Qiang Xue committed
314
	 *
Qiang Xue committed
315 316 317
	 * 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
318 319 320
	 * the rest of the name-value pairs in the array will be used to initialize
	 * the corresponding object properties.
	 *
Qiang Xue committed
321
	 * The object type can be either a class name or the [[getAlias|alias]] of
w  
Qiang Xue committed
322
	 * the class. For example,
w  
Qiang Xue committed
323
	 *
Qiang Xue committed
324
	 * - `\app\components\GoogleMap`: fully-qualified namespaced class.
Qiang Xue committed
325 326 327 328
	 * - `@app/components/GoogleMap`: an alias
	 *
	 * Below are some usage examples:
	 *
w  
Qiang Xue committed
329
	 * ~~~
Qiang Xue committed
330 331 332
	 * $object = \Yii::createObject('@app/components/GoogleMap');
	 * $object = \Yii::createObject(array(
	 *     'class' => '\app\components\GoogleMap',
w  
Qiang Xue committed
333 334 335 336
	 *     'apiKey' => 'xyz',
	 * ));
	 * ~~~
	 *
Qiang Xue committed
337 338 339 340 341 342 343 344 345 346
	 * This method can be used to create any object as long as the object's constructor is
	 * defined like the following:
	 *
	 * ~~~
	 * public function __construct(..., $config = array()) {
	 * }
	 * ~~~
	 *
	 * The method will pass the given configuration as the last parameter of the constructor,
	 * and any additional parameters to this method will be passed as the rest of the constructor parameters.
w  
Qiang Xue committed
347
	 *
Qiang Xue committed
348 349
	 * @param string|array $config the configuration. It can be either a string representing the class name
	 * or an array representing the object configuration.
w  
Qiang Xue committed
350
	 * @return mixed the created object
Qiang Xue committed
351
	 * @throws InvalidConfigException if the configuration is invalid.
w  
Qiang Xue committed
352
	 */
Qiang Xue committed
353
	public static function createObject($config)
w  
Qiang Xue committed
354
	{
Qiang Xue committed
355 356
		static $reflections = array();

w  
Qiang Xue committed
357
		if (is_string($config)) {
w  
Qiang Xue committed
358
			$class = $config;
w  
Qiang Xue committed
359
			$config = array();
Qiang Xue committed
360
		} elseif (isset($config['class'])) {
w  
Qiang Xue committed
361
			$class = $config['class'];
w  
Qiang Xue committed
362
			unset($config['class']);
Qiang Xue committed
363
		} else {
Qiang Xue committed
364
			throw new InvalidCallException('Object configuration must be an array containing a "class" element.');
w  
Qiang Xue committed
365 366
		}

w  
Qiang Xue committed
367 368
		if (!class_exists($class, false)) {
			$class = static::import($class, true);
w  
Qiang Xue committed
369 370
		}

Qiang Xue committed
371
		if (($n = func_num_args()) > 1) {
Qiang Xue committed
372 373 374
			/** @var $reflection \ReflectionClass */
			if (isset($reflections[$class])) {
				$reflection = $reflections[$class];
Qiang Xue committed
375
			} else {
Qiang Xue committed
376 377 378 379 380 381
				$reflection = $reflections[$class] = new \ReflectionClass($class);
			}
			$args = func_get_args();
			array_shift($args); // remove $config
			if ($config !== array()) {
				$args[] = $config;
Qiang Xue committed
382
			}
Qiang Xue committed
383
			return $reflection->newInstanceArgs($args);
Qiang Xue committed
384
		} else {
Qiang Xue committed
385
			return $config === array() ? new $class : new $class($config);
Qiang Xue committed
386
		}
w  
Qiang Xue committed
387 388
	}

Qiang Xue committed
389
	/**
w  
Qiang Xue committed
390 391 392 393 394
	 * 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
395
	 */
w  
Qiang Xue committed
396
	public static function trace($message, $category = 'application')
Qiang Xue committed
397
	{
w  
Qiang Xue committed
398
		if (YII_DEBUG) {
Qiang Xue committed
399
			self::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
w  
Qiang Xue committed
400
		}
Qiang Xue committed
401 402 403
	}

	/**
w  
Qiang Xue committed
404 405 406 407 408
	 * 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
409
	 */
Qiang Xue committed
410
	public static function error($message, $category = 'application')
Qiang Xue committed
411
	{
Qiang Xue committed
412
		self::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
w  
Qiang Xue committed
413 414 415 416 417 418 419 420 421
	}

	/**
	 * 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
422
	public static function warning($message, $category = 'application')
w  
Qiang Xue committed
423
	{
Qiang Xue committed
424
		self::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
Qiang Xue committed
425 426 427
	}

	/**
w  
Qiang Xue committed
428 429 430 431 432 433
	 * 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
434
	public static function info($message, $category = 'application')
w  
Qiang Xue committed
435
	{
Qiang Xue committed
436
		self::getLogger()->log($message, Logger::LEVEL_INFO, $category);
w  
Qiang Xue committed
437 438 439 440 441 442 443 444 445
	}

	/**
	 * 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
446 447 448 449
	 * // some code to be profiled
	 *     \Yii::beginProfile('block2');
	 *     // some other code to be profiled
	 *     \Yii::endProfile('block2');
w  
Qiang Xue committed
450 451
	 * \Yii::endProfile('block1');
	 * ~~~
Qiang Xue committed
452 453
	 * @param string $token token for the code block
	 * @param string $category the category of this log message
Qiang Xue committed
454 455
	 * @see endProfile
	 */
Qiang Xue committed
456
	public static function beginProfile($token, $category = 'application')
Qiang Xue committed
457
	{
Qiang Xue committed
458
		self::getLogger()->log($token, Logger::LEVEL_PROFILE_BEGIN, $category);
Qiang Xue committed
459 460 461 462
	}

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

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

	/**
	 * Sets the logger object.
Qiang Xue committed
488
	 * @param Logger $logger the logger object.
w  
Qiang Xue committed
489 490 491 492
	 */
	public static function setLogger($logger)
	{
		self::$_logger = $logger;
Qiang Xue committed
493 494 495
	}

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

w  
Qiang Xue committed
565
						$message = implode('|', $chunks);
Qiang Xue committed
566 567
					}
				}
w  
Qiang Xue committed
568
				$message = CChoiceFormat::format($message, $params[0]);
Qiang Xue committed
569
			}
w  
Qiang Xue committed
570
			if (!isset($params['{n}']))
Qiang Xue committed
571 572 573
					{
						$params['{n}'] = $params[0];
					}
Qiang Xue committed
574 575
			unset($params[0]);
		}
w  
Qiang Xue committed
576
		return $params !== array() ? strtr($message, $params) : $message;
Qiang Xue committed
577 578
	}
}