You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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.10';
  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 boolean $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|boolean 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. } else {
  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. }
  140. if ($throwException) {
  141. throw new InvalidParamException("Invalid path alias: $alias");
  142. } else {
  143. return false;
  144. }
  145. }
  146. /**
  147. * Returns the root alias part of a given alias.
  148. * A root alias is an alias that has been registered via [[setAlias()]] previously.
  149. * If a given alias matches multiple root aliases, the longest one will be returned.
  150. * @param string $alias the alias
  151. * @return string|boolean the root alias, or false if no root alias is found
  152. */
  153. public static function getRootAlias($alias)
  154. {
  155. $pos = strpos($alias, '/');
  156. $root = $pos === false ? $alias : substr($alias, 0, $pos);
  157. if (isset(static::$aliases[$root])) {
  158. if (is_string(static::$aliases[$root])) {
  159. return $root;
  160. } else {
  161. foreach (static::$aliases[$root] as $name => $path) {
  162. if (strpos($alias . '/', $name . '/') === 0) {
  163. return $name;
  164. }
  165. }
  166. }
  167. }
  168. return false;
  169. }
  170. /**
  171. * Registers a path alias.
  172. *
  173. * A path alias is a short name representing a long path (a file path, a URL, etc.)
  174. * For example, we use '@yii' as the alias of the path to the Yii framework directory.
  175. *
  176. * A path alias must start with the character '@' so that it can be easily differentiated
  177. * from non-alias paths.
  178. *
  179. * Note that this method does not check if the given path exists or not. All it does is
  180. * to associate the alias with the path.
  181. *
  182. * Any trailing '/' and '\' characters in the given path will be trimmed.
  183. *
  184. * @param string $alias the alias name (e.g. "@yii"). It must start with a '@' character.
  185. * It may contain the forward slash '/' which serves as boundary character when performing
  186. * alias translation by [[getAlias()]].
  187. * @param string $path the path corresponding to the alias. If this is null, the alias will
  188. * be removed. Trailing '/' and '\' characters will be trimmed. This can be
  189. *
  190. * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
  191. * - a URL (e.g. `http://www.yiiframework.com`)
  192. * - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the
  193. * actual path first by calling [[getAlias()]].
  194. *
  195. * @throws InvalidParamException if $path is an invalid alias.
  196. * @see getAlias()
  197. */
  198. public static function setAlias($alias, $path)
  199. {
  200. if (strncmp($alias, '@', 1)) {
  201. $alias = '@' . $alias;
  202. }
  203. $pos = strpos($alias, '/');
  204. $root = $pos === false ? $alias : substr($alias, 0, $pos);
  205. if ($path !== null) {
  206. $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
  207. if (!isset(static::$aliases[$root])) {
  208. if ($pos === false) {
  209. static::$aliases[$root] = $path;
  210. } else {
  211. static::$aliases[$root] = [$alias => $path];
  212. }
  213. } elseif (is_string(static::$aliases[$root])) {
  214. if ($pos === false) {
  215. static::$aliases[$root] = $path;
  216. } else {
  217. static::$aliases[$root] = [
  218. $alias => $path,
  219. $root => static::$aliases[$root],
  220. ];
  221. }
  222. } else {
  223. static::$aliases[$root][$alias] = $path;
  224. krsort(static::$aliases[$root]);
  225. }
  226. } elseif (isset(static::$aliases[$root])) {
  227. if (is_array(static::$aliases[$root])) {
  228. unset(static::$aliases[$root][$alias]);
  229. } elseif ($pos === false) {
  230. unset(static::$aliases[$root]);
  231. }
  232. }
  233. }
  234. /**
  235. * Class autoload loader.
  236. * This method is invoked automatically when PHP sees an unknown class.
  237. * The method will attempt to include the class file according to the following procedure:
  238. *
  239. * 1. Search in [[classMap]];
  240. * 2. If the class is namespaced (e.g. `yii\base\Component`), it will attempt
  241. * to include the file associated with the corresponding path alias
  242. * (e.g. `@yii/base/Component.php`);
  243. *
  244. * This autoloader allows loading classes that follow the [PSR-4 standard](http://www.php-fig.org/psr/psr-4/)
  245. * and have its top-level namespace or sub-namespaces defined as path aliases.
  246. *
  247. * Example: When aliases `@yii` and `@yii/bootstrap` are defined, classes in the `yii\bootstrap` namespace
  248. * will be loaded using the `@yii/bootstrap` alias which points to the directory where bootstrap extension
  249. * files are installed and all classes from other `yii` namespaces will be loaded from the yii framework directory.
  250. *
  251. * Also the [guide section on autoloading](guide:concept-autoloading).
  252. *
  253. * @param string $className the fully qualified class name without a leading backslash "\"
  254. * @throws UnknownClassException if the class does not exist in the class file
  255. */
  256. public static function autoload($className)
  257. {
  258. if (isset(static::$classMap[$className])) {
  259. $classFile = static::$classMap[$className];
  260. if ($classFile[0] === '@') {
  261. $classFile = static::getAlias($classFile);
  262. }
  263. } elseif (strpos($className, '\\') !== false) {
  264. $classFile = static::getAlias('@' . str_replace('\\', '/', $className) . '.php', false);
  265. if ($classFile === false || !is_file($classFile)) {
  266. return;
  267. }
  268. } else {
  269. return;
  270. }
  271. include($classFile);
  272. if (YII_DEBUG && !class_exists($className, false) && !interface_exists($className, false) && !trait_exists($className, false)) {
  273. throw new UnknownClassException("Unable to find '$className' in file: $classFile. Namespace missing?");
  274. }
  275. }
  276. /**
  277. * Creates a new object using the given configuration.
  278. *
  279. * You may view this method as an enhanced version of the `new` operator.
  280. * The method supports creating an object based on a class name, a configuration array or
  281. * an anonymous function.
  282. *
  283. * Below are some usage examples:
  284. *
  285. * ```php
  286. * // create an object using a class name
  287. * $object = Yii::createObject('yii\db\Connection');
  288. *
  289. * // create an object using a configuration array
  290. * $object = Yii::createObject([
  291. * 'class' => 'yii\db\Connection',
  292. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  293. * 'username' => 'root',
  294. * 'password' => '',
  295. * 'charset' => 'utf8',
  296. * ]);
  297. *
  298. * // create an object with two constructor parameters
  299. * $object = \Yii::createObject('MyClass', [$param1, $param2]);
  300. * ```
  301. *
  302. * Using [[\yii\di\Container|dependency injection container]], this method can also identify
  303. * dependent objects, instantiate them and inject them into the newly created object.
  304. *
  305. * @param string|array|callable $type the object type. This can be specified in one of the following forms:
  306. *
  307. * - a string: representing the class name of the object to be created
  308. * - a configuration array: the array must contain a `class` element which is treated as the object class,
  309. * and the rest of the name-value pairs will be used to initialize the corresponding object properties
  310. * - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`).
  311. * The callable should return a new instance of the object being created.
  312. *
  313. * @param array $params the constructor parameters
  314. * @return object the created object
  315. * @throws InvalidConfigException if the configuration is invalid.
  316. * @see \yii\di\Container
  317. */
  318. public static function createObject($type, array $params = [])
  319. {
  320. if (is_string($type)) {
  321. return static::$container->get($type, $params);
  322. } elseif (is_array($type) && isset($type['class'])) {
  323. $class = $type['class'];
  324. unset($type['class']);
  325. return static::$container->get($class, $params, $type);
  326. } elseif (is_callable($type, true)) {
  327. return static::$container->invoke($type, $params);
  328. } elseif (is_array($type)) {
  329. throw new InvalidConfigException('Object configuration must be an array containing a "class" element.');
  330. } else {
  331. throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
  332. }
  333. }
  334. private static $_logger;
  335. /**
  336. * @return Logger message logger
  337. */
  338. public static function getLogger()
  339. {
  340. if (self::$_logger !== null) {
  341. return self::$_logger;
  342. } else {
  343. return self::$_logger = static::createObject('yii\log\Logger');
  344. }
  345. }
  346. /**
  347. * Sets the logger object.
  348. * @param Logger $logger the logger object.
  349. */
  350. public static function setLogger($logger)
  351. {
  352. self::$_logger = $logger;
  353. }
  354. /**
  355. * Logs a trace message.
  356. * Trace messages are logged mainly for development purpose to see
  357. * the execution work flow of some code.
  358. * @param string $message the message to be logged.
  359. * @param string $category the category of the message.
  360. */
  361. public static function trace($message, $category = 'application')
  362. {
  363. if (YII_DEBUG) {
  364. static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
  365. }
  366. }
  367. /**
  368. * Logs an error message.
  369. * An error message is typically logged when an unrecoverable error occurs
  370. * during the execution of an application.
  371. * @param string $message the message to be logged.
  372. * @param string $category the category of the message.
  373. */
  374. public static function error($message, $category = 'application')
  375. {
  376. static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
  377. }
  378. /**
  379. * Logs a warning message.
  380. * A warning message is typically logged when an error occurs while the execution
  381. * can still continue.
  382. * @param string $message the message to be logged.
  383. * @param string $category the category of the message.
  384. */
  385. public static function warning($message, $category = 'application')
  386. {
  387. static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
  388. }
  389. /**
  390. * Logs an informative message.
  391. * An informative message is typically logged by an application to keep record of
  392. * something important (e.g. an administrator logs in).
  393. * @param string $message the message to be logged.
  394. * @param string $category the category of the message.
  395. */
  396. public static function info($message, $category = 'application')
  397. {
  398. static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
  399. }
  400. /**
  401. * Marks the beginning of a code block for profiling.
  402. * This has to be matched with a call to [[endProfile]] with the same category name.
  403. * The begin- and end- calls must also be properly nested. For example,
  404. *
  405. * ```php
  406. * \Yii::beginProfile('block1');
  407. * // some code to be profiled
  408. * \Yii::beginProfile('block2');
  409. * // some other code to be profiled
  410. * \Yii::endProfile('block2');
  411. * \Yii::endProfile('block1');
  412. * ```
  413. * @param string $token token for the code block
  414. * @param string $category the category of this log message
  415. * @see endProfile()
  416. */
  417. public static function beginProfile($token, $category = 'application')
  418. {
  419. static::getLogger()->log($token, Logger::LEVEL_PROFILE_BEGIN, $category);
  420. }
  421. /**
  422. * Marks the end of a code block for profiling.
  423. * This has to be matched with a previous call to [[beginProfile]] with the same category name.
  424. * @param string $token token for the code block
  425. * @param string $category the category of this log message
  426. * @see beginProfile()
  427. */
  428. public static function endProfile($token, $category = 'application')
  429. {
  430. static::getLogger()->log($token, Logger::LEVEL_PROFILE_END, $category);
  431. }
  432. /**
  433. * Returns an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information.
  434. * @return string an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information
  435. */
  436. public static function powered()
  437. {
  438. return \Yii::t('yii', 'Powered by {yii}', [
  439. 'yii' => '<a href="http://www.yiiframework.com/" rel="external">' . \Yii::t('yii',
  440. 'Yii Framework') . '</a>'
  441. ]);
  442. }
  443. /**
  444. * Translates a message to the specified language.
  445. *
  446. * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
  447. *
  448. * The translation will be conducted according to the message category and the target language will be used.
  449. *
  450. * You can add parameters to a translation message that will be substituted with the corresponding value after
  451. * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
  452. *
  453. * ```php
  454. * $username = 'Alexander';
  455. * echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
  456. * ```
  457. *
  458. * Further formatting of message parameters is supported using the [PHP intl extensions](http://www.php.net/manual/en/intro.intl.php)
  459. * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
  460. *
  461. * @param string $category the message category.
  462. * @param string $message the message to be translated.
  463. * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
  464. * @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
  465. * [[\yii\base\Application::language|application language]] will be used.
  466. * @return string the translated message.
  467. */
  468. public static function t($category, $message, $params = [], $language = null)
  469. {
  470. if (static::$app !== null) {
  471. return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
  472. } else {
  473. $p = [];
  474. foreach ((array) $params as $name => $value) {
  475. $p['{' . $name . '}'] = $value;
  476. }
  477. return ($p === []) ? $message : strtr($message, $p);
  478. }
  479. }
  480. /**
  481. * Configures an object with the initial property values.
  482. * @param object $object the object to be configured
  483. * @param array $properties the property initial values given in terms of name-value pairs.
  484. * @return object the object itself
  485. */
  486. public static function configure($object, $properties)
  487. {
  488. foreach ($properties as $name => $value) {
  489. $object->$name = $value;
  490. }
  491. return $object;
  492. }
  493. /**
  494. * Returns the public member variables of an object.
  495. * This method is provided such that we can get the public member variables of an object.
  496. * It is different from "get_object_vars()" because the latter will return private
  497. * and protected variables if it is called within the object itself.
  498. * @param object $object the object to be handled
  499. * @return array the public member variables of the object
  500. */
  501. public static function getObjectVars($object)
  502. {
  503. return get_object_vars($object);
  504. }
  505. }