BaseYii.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii;
  8. use yii\base\InvalidConfigException;
  9. use yii\base\InvalidParamException;
  10. use yii\base\UnknownClassException;
  11. use yii\log\Logger;
  12. use yii\di\Container;
  13. /**
  14. * Gets the application start timestamp.
  15. */
  16. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME', microtime(true));
  17. /**
  18. * This constant defines the framework installation directory.
  19. */
  20. defined('YII2_PATH') or define('YII2_PATH', __DIR__);
  21. /**
  22. * This constant defines whether the application should be in debug mode or not. Defaults to false.
  23. */
  24. defined('YII_DEBUG') or define('YII_DEBUG', false);
  25. /**
  26. * This constant defines in which environment the application is running. Defaults to 'prod', meaning production environment.
  27. * You may define this constant in the bootstrap script. The value could be 'prod' (production), 'dev' (development), 'test', 'staging', etc.
  28. */
  29. defined('YII_ENV') or define('YII_ENV', 'prod');
  30. /**
  31. * Whether the the application is running in production environment
  32. */
  33. defined('YII_ENV_PROD') or define('YII_ENV_PROD', YII_ENV === 'prod');
  34. /**
  35. * Whether the the application is running in development environment
  36. */
  37. defined('YII_ENV_DEV') or define('YII_ENV_DEV', YII_ENV === 'dev');
  38. /**
  39. * Whether the the application is running in testing environment
  40. */
  41. defined('YII_ENV_TEST') or define('YII_ENV_TEST', YII_ENV === 'test');
  42. /**
  43. * This constant defines whether error handling should be enabled. Defaults to true.
  44. */
  45. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true);
  46. /**
  47. * BaseYii is the core helper class for the Yii framework.
  48. *
  49. * Do not use BaseYii directly. Instead, use its child class [[\Yii]] which you can replace to
  50. * customize methods of BaseYii.
  51. *
  52. * @author Qiang Xue <qiang.xue@gmail.com>
  53. * @since 2.0
  54. */
  55. class BaseYii
  56. {
  57. /**
  58. * @var array class map used by the Yii autoloading mechanism.
  59. * The array keys are the class names (without leading backslashes), and the array values
  60. * are the corresponding class file paths (or path aliases). This property mainly affects
  61. * how [[autoload()]] works.
  62. * @see autoload()
  63. */
  64. public static $classMap = [];
  65. /**
  66. * @var \yii\console\Application|\yii\web\Application the application instance
  67. */
  68. public static $app;
  69. /**
  70. * @var array registered path aliases
  71. * @see getAlias()
  72. * @see setAlias()
  73. */
  74. public static $aliases = ['@yii' => __DIR__];
  75. /**
  76. * @var Container the dependency injection (DI) container used by [[createObject()]].
  77. * You may use [[Container::set()]] to set up the needed dependencies of classes and
  78. * their initial property values.
  79. * @see createObject()
  80. * @see Container
  81. */
  82. public static $container;
  83. /**
  84. * Returns a string representing the current version of the Yii framework.
  85. * @return string the version of Yii framework
  86. */
  87. public static function getVersion()
  88. {
  89. return '2.0.11';
  90. }
  91. /**
  92. * Translates a path alias into an actual path.
  93. *
  94. * The translation is done according to the following procedure:
  95. *
  96. * 1. If the given alias does not start with '@', it is returned back without change;
  97. * 2. Otherwise, look for the longest registered alias that matches the beginning part
  98. * of the given alias. If it exists, replace the matching part of the given alias with
  99. * the corresponding registered path.
  100. * 3. Throw an exception or return false, depending on the `$throwException` parameter.
  101. *
  102. * For example, by default '@yii' is registered as the alias to the Yii framework directory,
  103. * say '/path/to/yii'. The alias '@yii/web' would then be translated into '/path/to/yii/web'.
  104. *
  105. * If you have registered two aliases '@foo' and '@foo/bar'. Then translating '@foo/bar/config'
  106. * would replace the part '@foo/bar' (instead of '@foo') with the corresponding registered path.
  107. * This is because the longest alias takes precedence.
  108. *
  109. * However, if the alias to be translated is '@foo/barbar/config', then '@foo' will be replaced
  110. * instead of '@foo/bar', because '/' serves as the boundary character.
  111. *
  112. * Note, this method does not check if the returned path exists or not.
  113. *
  114. * @param string $alias the alias to be translated.
  115. * @param bool $throwException whether to throw an exception if the given alias is invalid.
  116. * If this is false and an invalid alias is given, false will be returned by this method.
  117. * @return string|bool the path corresponding to the alias, false if the root alias is not previously registered.
  118. * @throws InvalidParamException if the alias is invalid while $throwException is true.
  119. * @see setAlias()
  120. */
  121. public static function getAlias($alias, $throwException = true)
  122. {
  123. if (strncmp($alias, '@', 1)) {
  124. // not an alias
  125. return $alias;
  126. }
  127. $pos = strpos($alias, '/');
  128. $root = $pos === false ? $alias : substr($alias, 0, $pos);
  129. if (isset(static::$aliases[$root])) {
  130. if (is_string(static::$aliases[$root])) {
  131. return $pos === false ? static::$aliases[$root] : static::$aliases[$root] . substr($alias, $pos);
  132. }
  133. foreach (static::$aliases[$root] as $name => $path) {
  134. if (strpos($alias . '/', $name . '/') === 0) {
  135. return $path . substr($alias, strlen($name));
  136. }
  137. }
  138. }
  139. if ($throwException) {
  140. throw new InvalidParamException("Invalid path alias: $alias");
  141. }
  142. return false;
  143. }
  144. /**
  145. * Returns the root alias part of a given alias.
  146. * A root alias is an alias that has been registered via [[setAlias()]] previously.
  147. * If a given alias matches multiple root aliases, the longest one will be returned.
  148. * @param string $alias the alias
  149. * @return string|bool the root alias, or false if no root alias is found
  150. */
  151. public static function getRootAlias($alias)
  152. {
  153. $pos = strpos($alias, '/');
  154. $root = $pos === false ? $alias : substr($alias, 0, $pos);
  155. if (isset(static::$aliases[$root])) {
  156. if (is_string(static::$aliases[$root])) {
  157. return $root;
  158. }
  159. foreach (static::$aliases[$root] as $name => $path) {
  160. if (strpos($alias . '/', $name . '/') === 0) {
  161. return $name;
  162. }
  163. }
  164. }
  165. return false;
  166. }
  167. /**
  168. * Registers a path alias.
  169. *
  170. * A path alias is a short name representing a long path (a file path, a URL, etc.)
  171. * For example, we use '@yii' as the alias of the path to the Yii framework directory.
  172. *
  173. * A path alias must start with the character '@' so that it can be easily differentiated
  174. * from non-alias paths.
  175. *
  176. * Note that this method does not check if the given path exists or not. All it does is
  177. * to associate the alias with the path.
  178. *
  179. * Any trailing '/' and '\' characters in the given path will be trimmed.
  180. *
  181. * @param string $alias the alias name (e.g. "@yii"). It must start with a '@' character.
  182. * It may contain the forward slash '/' which serves as boundary character when performing
  183. * alias translation by [[getAlias()]].
  184. * @param string $path the path corresponding to the alias. If this is null, the alias will
  185. * be removed. Trailing '/' and '\' characters will be trimmed. This can be
  186. *
  187. * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
  188. * - a URL (e.g. `http://www.yiiframework.com`)
  189. * - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the
  190. * actual path first by calling [[getAlias()]].
  191. *
  192. * @throws InvalidParamException if $path is an invalid alias.
  193. * @see getAlias()
  194. */
  195. public static function setAlias($alias, $path)
  196. {
  197. if (strncmp($alias, '@', 1)) {
  198. $alias = '@' . $alias;
  199. }
  200. $pos = strpos($alias, '/');
  201. $root = $pos === false ? $alias : substr($alias, 0, $pos);
  202. if ($path !== null) {
  203. $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
  204. if (!isset(static::$aliases[$root])) {
  205. if ($pos === false) {
  206. static::$aliases[$root] = $path;
  207. } else {
  208. static::$aliases[$root] = [$alias => $path];
  209. }
  210. } elseif (is_string(static::$aliases[$root])) {
  211. if ($pos === false) {
  212. static::$aliases[$root] = $path;
  213. } else {
  214. static::$aliases[$root] = [
  215. $alias => $path,
  216. $root => static::$aliases[$root],
  217. ];
  218. }
  219. } else {
  220. static::$aliases[$root][$alias] = $path;
  221. krsort(static::$aliases[$root]);
  222. }
  223. } elseif (isset(static::$aliases[$root])) {
  224. if (is_array(static::$aliases[$root])) {
  225. unset(static::$aliases[$root][$alias]);
  226. } elseif ($pos === false) {
  227. unset(static::$aliases[$root]);
  228. }
  229. }
  230. }
  231. /**
  232. * Class autoload loader.
  233. * This method is invoked automatically when PHP sees an unknown class.
  234. * The method will attempt to include the class file according to the following procedure:
  235. *
  236. * 1. Search in [[classMap]];
  237. * 2. If the class is namespaced (e.g. `yii\base\Component`), it will attempt
  238. * to include the file associated with the corresponding path alias
  239. * (e.g. `@yii/base/Component.php`);
  240. *
  241. * This autoloader allows loading classes that follow the [PSR-4 standard](http://www.php-fig.org/psr/psr-4/)
  242. * and have its top-level namespace or sub-namespaces defined as path aliases.
  243. *
  244. * Example: When aliases `@yii` and `@yii/bootstrap` are defined, classes in the `yii\bootstrap` namespace
  245. * will be loaded using the `@yii/bootstrap` alias which points to the directory where bootstrap extension
  246. * files are installed and all classes from other `yii` namespaces will be loaded from the yii framework directory.
  247. *
  248. * Also the [guide section on autoloading](guide:concept-autoloading).
  249. *
  250. * @param string $className the fully qualified class name without a leading backslash "\"
  251. * @throws UnknownClassException if the class does not exist in the class file
  252. */
  253. public static function autoload($className)
  254. {
  255. if (isset(static::$classMap[$className])) {
  256. $classFile = static::$classMap[$className];
  257. if ($classFile[0] === '@') {
  258. $classFile = static::getAlias($classFile);
  259. }
  260. } elseif (strpos($className, '\\') !== false) {
  261. $classFile = static::getAlias('@' . str_replace('\\', '/', $className) . '.php', false);
  262. if ($classFile === false || !is_file($classFile)) {
  263. return;
  264. }
  265. } else {
  266. return;
  267. }
  268. include($classFile);
  269. if (YII_DEBUG && !class_exists($className, false) && !interface_exists($className, false) && !trait_exists($className, false)) {
  270. throw new UnknownClassException("Unable to find '$className' in file: $classFile. Namespace missing?");
  271. }
  272. }
  273. /**
  274. * Creates a new object using the given configuration.
  275. *
  276. * You may view this method as an enhanced version of the `new` operator.
  277. * The method supports creating an object based on a class name, a configuration array or
  278. * an anonymous function.
  279. *
  280. * Below are some usage examples:
  281. *
  282. * ```php
  283. * // create an object using a class name
  284. * $object = Yii::createObject('yii\db\Connection');
  285. *
  286. * // create an object using a configuration array
  287. * $object = Yii::createObject([
  288. * 'class' => 'yii\db\Connection',
  289. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  290. * 'username' => 'root',
  291. * 'password' => '',
  292. * 'charset' => 'utf8',
  293. * ]);
  294. *
  295. * // create an object with two constructor parameters
  296. * $object = \Yii::createObject('MyClass', [$param1, $param2]);
  297. * ```
  298. *
  299. * Using [[\yii\di\Container|dependency injection container]], this method can also identify
  300. * dependent objects, instantiate them and inject them into the newly created object.
  301. *
  302. * @param string|array|callable $type the object type. This can be specified in one of the following forms:
  303. *
  304. * - a string: representing the class name of the object to be created
  305. * - a configuration array: the array must contain a `class` element which is treated as the object class,
  306. * and the rest of the name-value pairs will be used to initialize the corresponding object properties
  307. * - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`).
  308. * The callable should return a new instance of the object being created.
  309. *
  310. * @param array $params the constructor parameters
  311. * @return object the created object
  312. * @throws InvalidConfigException if the configuration is invalid.
  313. * @see \yii\di\Container
  314. */
  315. public static function createObject($type, array $params = [])
  316. {
  317. if (is_string($type)) {
  318. return static::$container->get($type, $params);
  319. } elseif (is_array($type) && isset($type['class'])) {
  320. $class = $type['class'];
  321. unset($type['class']);
  322. return static::$container->get($class, $params, $type);
  323. } elseif (is_callable($type, true)) {
  324. return static::$container->invoke($type, $params);
  325. } elseif (is_array($type)) {
  326. throw new InvalidConfigException('Object configuration must be an array containing a "class" element.');
  327. }
  328. throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
  329. }
  330. private static $_logger;
  331. /**
  332. * @return Logger message logger
  333. */
  334. public static function getLogger()
  335. {
  336. if (self::$_logger !== null) {
  337. return self::$_logger;
  338. }
  339. return self::$_logger = static::createObject('yii\log\Logger');
  340. }
  341. /**
  342. * Sets the logger object.
  343. * @param Logger $logger the logger object.
  344. */
  345. public static function setLogger($logger)
  346. {
  347. self::$_logger = $logger;
  348. }
  349. /**
  350. * Logs a trace message.
  351. * Trace messages are logged mainly for development purpose to see
  352. * the execution work flow of some code.
  353. * @param string|array $message the message to be logged. This can be a simple string or a more
  354. * complex data structure, such as array.
  355. * @param string $category the category of the message.
  356. */
  357. public static function trace($message, $category = 'application')
  358. {
  359. if (YII_DEBUG) {
  360. static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
  361. }
  362. }
  363. /**
  364. * Logs an error message.
  365. * An error message is typically logged when an unrecoverable error occurs
  366. * during the execution of an application.
  367. * @param string|array $message the message to be logged. This can be a simple string or a more
  368. * complex data structure, such as array.
  369. * @param string $category the category of the message.
  370. */
  371. public static function error($message, $category = 'application')
  372. {
  373. static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
  374. }
  375. /**
  376. * Logs a warning message.
  377. * A warning message is typically logged when an error occurs while the execution
  378. * can still continue.
  379. * @param string|array $message the message to be logged. This can be a simple string or a more
  380. * complex data structure, such as array.
  381. * @param string $category the category of the message.
  382. */
  383. public static function warning($message, $category = 'application')
  384. {
  385. static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
  386. }
  387. /**
  388. * Logs an informative message.
  389. * An informative message is typically logged by an application to keep record of
  390. * something important (e.g. an administrator logs in).
  391. * @param string|array $message the message to be logged. This can be a simple string or a more
  392. * complex data structure, such as array.
  393. * @param string $category the category of the message.
  394. */
  395. public static function info($message, $category = 'application')
  396. {
  397. static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
  398. }
  399. /**
  400. * Marks the beginning of a code block for profiling.
  401. * This has to be matched with a call to [[endProfile]] with the same category name.
  402. * The begin- and end- calls must also be properly nested. For example,
  403. *
  404. * ```php
  405. * \Yii::beginProfile('block1');
  406. * // some code to be profiled
  407. * \Yii::beginProfile('block2');
  408. * // some other code to be profiled
  409. * \Yii::endProfile('block2');
  410. * \Yii::endProfile('block1');
  411. * ```
  412. * @param string $token token for the code block
  413. * @param string $category the category of this log message
  414. * @see endProfile()
  415. */
  416. public static function beginProfile($token, $category = 'application')
  417. {
  418. static::getLogger()->log($token, Logger::LEVEL_PROFILE_BEGIN, $category);
  419. }
  420. /**
  421. * Marks the end of a code block for profiling.
  422. * This has to be matched with a previous call to [[beginProfile]] with the same category name.
  423. * @param string $token token for the code block
  424. * @param string $category the category of this log message
  425. * @see beginProfile()
  426. */
  427. public static function endProfile($token, $category = 'application')
  428. {
  429. static::getLogger()->log($token, Logger::LEVEL_PROFILE_END, $category);
  430. }
  431. /**
  432. * Returns an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information.
  433. * @return string an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information
  434. */
  435. public static function powered()
  436. {
  437. return \Yii::t('yii', 'Powered by {yii}', [
  438. 'yii' => '<a href="http://www.yiiframework.com/" rel="external">' . \Yii::t('yii',
  439. 'Yii Framework') . '</a>'
  440. ]);
  441. }
  442. /**
  443. * Translates a message to the specified language.
  444. *
  445. * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
  446. *
  447. * The translation will be conducted according to the message category and the target language will be used.
  448. *
  449. * You can add parameters to a translation message that will be substituted with the corresponding value after
  450. * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
  451. *
  452. * ```php
  453. * $username = 'Alexander';
  454. * echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
  455. * ```
  456. *
  457. * Further formatting of message parameters is supported using the [PHP intl extensions](http://www.php.net/manual/en/intro.intl.php)
  458. * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
  459. *
  460. * @param string $category the message category.
  461. * @param string $message the message to be translated.
  462. * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
  463. * @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
  464. * [[\yii\base\Application::language|application language]] will be used.
  465. * @return string the translated message.
  466. */
  467. public static function t($category, $message, $params = [], $language = null)
  468. {
  469. if (static::$app !== null) {
  470. return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
  471. }
  472. $placeholders = [];
  473. foreach ((array) $params as $name => $value) {
  474. $placeholders['{' . $name . '}'] = $value;
  475. }
  476. return ($placeholders === []) ? $message : strtr($message, $placeholders);
  477. }
  478. /**
  479. * Configures an object with the initial property values.
  480. * @param object $object the object to be configured
  481. * @param array $properties the property initial values given in terms of name-value pairs.
  482. * @return object the object itself
  483. */
  484. public static function configure($object, $properties)
  485. {
  486. foreach ($properties as $name => $value) {
  487. $object->$name = $value;
  488. }
  489. return $object;
  490. }
  491. /**
  492. * Returns the public member variables of an object.
  493. * This method is provided such that we can get the public member variables of an object.
  494. * It is different from "get_object_vars()" because the latter will return private
  495. * and protected variables if it is called within the object itself.
  496. * @param object $object the object to be handled
  497. * @return array the public member variables of the object
  498. */
  499. public static function getObjectVars($object)
  500. {
  501. return get_object_vars($object);
  502. }
  503. }