Application.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. /**
  10. * Application is the base class for all application classes.
  11. *
  12. * For more details and usage information on Application, see the [guide article on applications](guide:structure-applications).
  13. *
  14. * @property-read \yii\web\AssetManager $assetManager The asset manager application component.
  15. * @property-read \yii\rbac\ManagerInterface|null $authManager The auth manager application component or null
  16. * if it's not configured.
  17. * @property string $basePath The root directory of the application.
  18. * @property-read \yii\caching\CacheInterface|null $cache The cache application component. Null if the
  19. * component is not enabled.
  20. * @property-write array $container Values given in terms of name-value pairs.
  21. * @property-read \yii\db\Connection $db The database connection.
  22. * @property-read \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application
  23. * component.
  24. * @property-read \yii\i18n\Formatter $formatter The formatter application component.
  25. * @property-read \yii\i18n\I18N $i18n The internationalization application component.
  26. * @property-read \yii\log\Dispatcher $log The log dispatcher application component.
  27. * @property-read \yii\mail\MailerInterface $mailer The mailer application component.
  28. * @property-read \yii\web\Request|\yii\console\Request $request The request component.
  29. * @property-read \yii\web\Response|\yii\console\Response $response The response component.
  30. * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
  31. * subdirectory under [[basePath]].
  32. * @property-read \yii\base\Security $security The security application component.
  33. * @property string $timeZone The time zone used by this application.
  34. * @property-read string $uniqueId The unique ID of the module.
  35. * @property-read \yii\web\UrlManager $urlManager The URL manager for this application.
  36. * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
  37. * [[basePath]].
  38. * @property-read View|\yii\web\View $view The view application component that is used to render various view
  39. * files.
  40. *
  41. * @author Qiang Xue <qiang.xue@gmail.com>
  42. * @since 2.0
  43. */
  44. abstract class Application extends Module
  45. {
  46. /**
  47. * @event Event an event raised before the application starts to handle a request.
  48. */
  49. const EVENT_BEFORE_REQUEST = 'beforeRequest';
  50. /**
  51. * @event Event an event raised after the application successfully handles a request (before the response is sent out).
  52. */
  53. const EVENT_AFTER_REQUEST = 'afterRequest';
  54. /**
  55. * Application state used by [[state]]: application just started.
  56. */
  57. const STATE_BEGIN = 0;
  58. /**
  59. * Application state used by [[state]]: application is initializing.
  60. */
  61. const STATE_INIT = 1;
  62. /**
  63. * Application state used by [[state]]: application is triggering [[EVENT_BEFORE_REQUEST]].
  64. */
  65. const STATE_BEFORE_REQUEST = 2;
  66. /**
  67. * Application state used by [[state]]: application is handling the request.
  68. */
  69. const STATE_HANDLING_REQUEST = 3;
  70. /**
  71. * Application state used by [[state]]: application is triggering [[EVENT_AFTER_REQUEST]]..
  72. */
  73. const STATE_AFTER_REQUEST = 4;
  74. /**
  75. * Application state used by [[state]]: application is about to send response.
  76. */
  77. const STATE_SENDING_RESPONSE = 5;
  78. /**
  79. * Application state used by [[state]]: application has ended.
  80. */
  81. const STATE_END = 6;
  82. /**
  83. * @var string the namespace that controller classes are located in.
  84. * This namespace will be used to load controller classes by prepending it to the controller class name.
  85. * The default namespace is `app\controllers`.
  86. *
  87. * Please refer to the [guide about class autoloading](guide:concept-autoloading.md) for more details.
  88. */
  89. public $controllerNamespace = 'app\\controllers';
  90. /**
  91. * @var string the application name.
  92. */
  93. public $name = 'My Application';
  94. /**
  95. * @var string the charset currently used for the application.
  96. */
  97. public $charset = 'UTF-8';
  98. /**
  99. * @var string the language that is meant to be used for end users. It is recommended that you
  100. * use [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag). For example, `en` stands
  101. * for English, while `en-US` stands for English (United States).
  102. * @see sourceLanguage
  103. */
  104. public $language = 'en-US';
  105. /**
  106. * @var string the language that the application is written in. This mainly refers to
  107. * the language that the messages and view files are written in.
  108. * @see language
  109. */
  110. public $sourceLanguage = 'en-US';
  111. /**
  112. * @var Controller the currently active controller instance
  113. */
  114. public $controller;
  115. /**
  116. * @var string|bool the layout that should be applied for views in this application. Defaults to 'main'.
  117. * If this is false, layout will be disabled.
  118. */
  119. public $layout = 'main';
  120. /**
  121. * @var string the requested route
  122. */
  123. public $requestedRoute;
  124. /**
  125. * @var Action|null the requested Action. If null, it means the request cannot be resolved into an action.
  126. */
  127. public $requestedAction;
  128. /**
  129. * @var array the parameters supplied to the requested action.
  130. */
  131. public $requestedParams;
  132. /**
  133. * @var array|null list of installed Yii extensions. Each array element represents a single extension
  134. * with the following structure:
  135. *
  136. * ```php
  137. * [
  138. * 'name' => 'extension name',
  139. * 'version' => 'version number',
  140. * 'bootstrap' => 'BootstrapClassName', // optional, may also be a configuration array
  141. * 'alias' => [
  142. * '@alias1' => 'to/path1',
  143. * '@alias2' => 'to/path2',
  144. * ],
  145. * ]
  146. * ```
  147. *
  148. * The "bootstrap" class listed above will be instantiated during the application
  149. * [[bootstrap()|bootstrapping process]]. If the class implements [[BootstrapInterface]],
  150. * its [[BootstrapInterface::bootstrap()|bootstrap()]] method will be also be called.
  151. *
  152. * If not set explicitly in the application config, this property will be populated with the contents of
  153. * `@vendor/yiisoft/extensions.php`.
  154. */
  155. public $extensions;
  156. /**
  157. * @var array list of components that should be run during the application [[bootstrap()|bootstrapping process]].
  158. *
  159. * Each component may be specified in one of the following formats:
  160. *
  161. * - an application component ID as specified via [[components]].
  162. * - a module ID as specified via [[modules]].
  163. * - a class name.
  164. * - a configuration array.
  165. * - a Closure
  166. *
  167. * During the bootstrapping process, each component will be instantiated. If the component class
  168. * implements [[BootstrapInterface]], its [[BootstrapInterface::bootstrap()|bootstrap()]] method
  169. * will be also be called.
  170. */
  171. public $bootstrap = [];
  172. /**
  173. * @var int the current application state during a request handling life cycle.
  174. * This property is managed by the application. Do not modify this property.
  175. */
  176. public $state;
  177. /**
  178. * @var array list of loaded modules indexed by their class names.
  179. */
  180. public $loadedModules = [];
  181. /**
  182. * Constructor.
  183. * @param array $config name-value pairs that will be used to initialize the object properties.
  184. * Note that the configuration must contain both [[id]] and [[basePath]].
  185. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  186. *
  187. * @phpstan-param array<string, mixed> $config
  188. * @psalm-param array<string, mixed> $config
  189. */
  190. public function __construct($config = [])
  191. {
  192. Yii::$app = $this;
  193. static::setInstance($this);
  194. $this->state = self::STATE_BEGIN;
  195. $this->preInit($config);
  196. $this->registerErrorHandler($config);
  197. Component::__construct($config);
  198. }
  199. /**
  200. * Pre-initializes the application.
  201. * This method is called at the beginning of the application constructor.
  202. * It initializes several important application properties.
  203. * If you override this method, please make sure you call the parent implementation.
  204. * @param array $config the application configuration
  205. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  206. */
  207. public function preInit(&$config)
  208. {
  209. if (!isset($config['id'])) {
  210. throw new InvalidConfigException('The "id" configuration for the Application is required.');
  211. }
  212. if (isset($config['basePath'])) {
  213. $this->setBasePath($config['basePath']);
  214. unset($config['basePath']);
  215. } else {
  216. throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
  217. }
  218. if (isset($config['vendorPath'])) {
  219. $this->setVendorPath($config['vendorPath']);
  220. unset($config['vendorPath']);
  221. } else {
  222. // set "@vendor"
  223. $this->getVendorPath();
  224. }
  225. if (isset($config['runtimePath'])) {
  226. $this->setRuntimePath($config['runtimePath']);
  227. unset($config['runtimePath']);
  228. } else {
  229. // set "@runtime"
  230. $this->getRuntimePath();
  231. }
  232. if (isset($config['timeZone'])) {
  233. $this->setTimeZone($config['timeZone']);
  234. unset($config['timeZone']);
  235. } elseif (!ini_get('date.timezone')) {
  236. $this->setTimeZone('UTC');
  237. }
  238. if (isset($config['container'])) {
  239. $this->setContainer($config['container']);
  240. unset($config['container']);
  241. }
  242. // merge core components with custom components
  243. foreach ($this->coreComponents() as $id => $component) {
  244. if (!isset($config['components'][$id])) {
  245. $config['components'][$id] = $component;
  246. } elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
  247. $config['components'][$id]['class'] = $component['class'];
  248. }
  249. }
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function init()
  255. {
  256. $this->state = self::STATE_INIT;
  257. $this->bootstrap();
  258. }
  259. /**
  260. * Initializes extensions and executes bootstrap components.
  261. * This method is called by [[init()]] after the application has been fully configured.
  262. * If you override this method, make sure you also call the parent implementation.
  263. */
  264. protected function bootstrap()
  265. {
  266. if ($this->extensions === null) {
  267. $file = Yii::getAlias('@vendor/yiisoft/extensions.php');
  268. $this->extensions = is_file($file) ? include $file : [];
  269. }
  270. foreach ($this->extensions as $extension) {
  271. if (!empty($extension['alias'])) {
  272. foreach ($extension['alias'] as $name => $path) {
  273. Yii::setAlias($name, $path);
  274. }
  275. }
  276. if (isset($extension['bootstrap'])) {
  277. $component = Yii::createObject($extension['bootstrap']);
  278. if ($component instanceof BootstrapInterface) {
  279. Yii::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
  280. $component->bootstrap($this);
  281. } else {
  282. Yii::debug('Bootstrap with ' . get_class($component), __METHOD__);
  283. }
  284. }
  285. }
  286. foreach ($this->bootstrap as $mixed) {
  287. $component = null;
  288. if ($mixed instanceof \Closure) {
  289. Yii::debug('Bootstrap with Closure', __METHOD__);
  290. if (!$component = call_user_func($mixed, $this)) {
  291. continue;
  292. }
  293. } elseif (is_string($mixed)) {
  294. if ($this->has($mixed)) {
  295. $component = $this->get($mixed);
  296. } elseif ($this->hasModule($mixed)) {
  297. $component = $this->getModule($mixed);
  298. } elseif (strpos($mixed, '\\') === false) {
  299. throw new InvalidConfigException("Unknown bootstrapping component ID: $mixed");
  300. }
  301. }
  302. if (!isset($component)) {
  303. $component = Yii::createObject($mixed);
  304. }
  305. if ($component instanceof BootstrapInterface) {
  306. Yii::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
  307. $component->bootstrap($this);
  308. } else {
  309. Yii::debug('Bootstrap with ' . get_class($component), __METHOD__);
  310. }
  311. }
  312. }
  313. /**
  314. * Registers the errorHandler component as a PHP error handler.
  315. * @param array $config application config
  316. */
  317. protected function registerErrorHandler(&$config)
  318. {
  319. if (YII_ENABLE_ERROR_HANDLER) {
  320. if (!isset($config['components']['errorHandler']['class'])) {
  321. echo "Error: no errorHandler component is configured.\n";
  322. exit(1);
  323. }
  324. $this->set('errorHandler', $config['components']['errorHandler']);
  325. unset($config['components']['errorHandler']);
  326. $this->getErrorHandler()->register();
  327. }
  328. }
  329. /**
  330. * Returns an ID that uniquely identifies this module among all modules within the current application.
  331. * Since this is an application instance, it will always return an empty string.
  332. * @return string the unique ID of the module.
  333. */
  334. public function getUniqueId()
  335. {
  336. return '';
  337. }
  338. /**
  339. * Sets the root directory of the application and the @app alias.
  340. * This method can only be invoked at the beginning of the constructor.
  341. * @param string $path the root directory of the application.
  342. * @property string the root directory of the application.
  343. * @throws InvalidArgumentException if the directory does not exist.
  344. */
  345. public function setBasePath($path)
  346. {
  347. parent::setBasePath($path);
  348. Yii::setAlias('@app', $this->getBasePath());
  349. }
  350. /**
  351. * Runs the application.
  352. * This is the main entrance of an application.
  353. * @return int the exit status (0 means normal, non-zero values mean abnormal)
  354. */
  355. public function run()
  356. {
  357. try {
  358. $this->state = self::STATE_BEFORE_REQUEST;
  359. $this->trigger(self::EVENT_BEFORE_REQUEST);
  360. $this->state = self::STATE_HANDLING_REQUEST;
  361. $response = $this->handleRequest($this->getRequest());
  362. $this->state = self::STATE_AFTER_REQUEST;
  363. $this->trigger(self::EVENT_AFTER_REQUEST);
  364. $this->state = self::STATE_SENDING_RESPONSE;
  365. $response->send();
  366. $this->state = self::STATE_END;
  367. return $response->exitStatus;
  368. } catch (ExitException $e) {
  369. $this->end($e->statusCode, isset($response) ? $response : null);
  370. return $e->statusCode;
  371. }
  372. }
  373. /**
  374. * Handles the specified request.
  375. *
  376. * This method should return an instance of [[Response]] or its child class
  377. * which represents the handling result of the request.
  378. *
  379. * @param Request $request the request to be handled
  380. * @return Response the resulting response
  381. */
  382. abstract public function handleRequest($request);
  383. private $_runtimePath;
  384. /**
  385. * Returns the directory that stores runtime files.
  386. * @return string the directory that stores runtime files.
  387. * Defaults to the "runtime" subdirectory under [[basePath]].
  388. */
  389. public function getRuntimePath()
  390. {
  391. if ($this->_runtimePath === null) {
  392. $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
  393. }
  394. return $this->_runtimePath;
  395. }
  396. /**
  397. * Sets the directory that stores runtime files.
  398. * @param string $path the directory that stores runtime files.
  399. */
  400. public function setRuntimePath($path)
  401. {
  402. $this->_runtimePath = Yii::getAlias($path);
  403. Yii::setAlias('@runtime', $this->_runtimePath);
  404. }
  405. private $_vendorPath;
  406. /**
  407. * Returns the directory that stores vendor files.
  408. * @return string the directory that stores vendor files.
  409. * Defaults to "vendor" directory under [[basePath]].
  410. */
  411. public function getVendorPath()
  412. {
  413. if ($this->_vendorPath === null) {
  414. $this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
  415. }
  416. return $this->_vendorPath;
  417. }
  418. /**
  419. * Sets the directory that stores vendor files.
  420. * @param string $path the directory that stores vendor files.
  421. */
  422. public function setVendorPath($path)
  423. {
  424. $this->_vendorPath = Yii::getAlias($path);
  425. Yii::setAlias('@vendor', $this->_vendorPath);
  426. Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower');
  427. Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');
  428. }
  429. /**
  430. * Returns the time zone used by this application.
  431. * This is a simple wrapper of PHP function date_default_timezone_get().
  432. * If time zone is not configured in php.ini or application config,
  433. * it will be set to UTC by default.
  434. * @return string the time zone used by this application.
  435. * @see https://www.php.net/manual/en/function.date-default-timezone-get.php
  436. */
  437. public function getTimeZone()
  438. {
  439. return date_default_timezone_get();
  440. }
  441. /**
  442. * Sets the time zone used by this application.
  443. * This is a simple wrapper of PHP function date_default_timezone_set().
  444. * Refer to the [php manual](https://www.php.net/manual/en/timezones.php) for available timezones.
  445. * @param string $value the time zone used by this application.
  446. * @see https://www.php.net/manual/en/function.date-default-timezone-set.php
  447. */
  448. public function setTimeZone($value)
  449. {
  450. date_default_timezone_set($value);
  451. }
  452. /**
  453. * Returns the database connection component.
  454. * @return \yii\db\Connection the database connection.
  455. */
  456. public function getDb()
  457. {
  458. return $this->get('db');
  459. }
  460. /**
  461. * Returns the log dispatcher component.
  462. * @return \yii\log\Dispatcher the log dispatcher application component.
  463. */
  464. public function getLog()
  465. {
  466. return $this->get('log');
  467. }
  468. /**
  469. * Returns the error handler component.
  470. * @return \yii\web\ErrorHandler|\yii\console\ErrorHandler the error handler application component.
  471. */
  472. public function getErrorHandler()
  473. {
  474. return $this->get('errorHandler');
  475. }
  476. /**
  477. * Returns the cache component.
  478. * @return \yii\caching\CacheInterface|null the cache application component. Null if the component is not enabled.
  479. */
  480. public function getCache()
  481. {
  482. return $this->get('cache', false);
  483. }
  484. /**
  485. * Returns the formatter component.
  486. * @return \yii\i18n\Formatter the formatter application component.
  487. */
  488. public function getFormatter()
  489. {
  490. return $this->get('formatter');
  491. }
  492. /**
  493. * Returns the request component.
  494. * @return \yii\web\Request|\yii\console\Request the request component.
  495. */
  496. public function getRequest()
  497. {
  498. return $this->get('request');
  499. }
  500. /**
  501. * Returns the response component.
  502. * @return \yii\web\Response|\yii\console\Response the response component.
  503. */
  504. public function getResponse()
  505. {
  506. return $this->get('response');
  507. }
  508. /**
  509. * Returns the view object.
  510. * @return View|\yii\web\View the view application component that is used to render various view files.
  511. */
  512. public function getView()
  513. {
  514. return $this->get('view');
  515. }
  516. /**
  517. * Returns the URL manager for this application.
  518. * @return \yii\web\UrlManager the URL manager for this application.
  519. */
  520. public function getUrlManager()
  521. {
  522. return $this->get('urlManager');
  523. }
  524. /**
  525. * Returns the internationalization (i18n) component.
  526. * @return \yii\i18n\I18N the internationalization application component.
  527. */
  528. public function getI18n()
  529. {
  530. return $this->get('i18n');
  531. }
  532. /**
  533. * Returns the mailer component.
  534. * @return \yii\mail\MailerInterface the mailer application component.
  535. * @throws InvalidConfigException If this component is not configured.
  536. */
  537. public function getMailer()
  538. {
  539. return $this->get('mailer');
  540. }
  541. /**
  542. * Returns the auth manager for this application.
  543. * @return \yii\rbac\ManagerInterface|null the auth manager application component or null if it's not configured.
  544. */
  545. public function getAuthManager()
  546. {
  547. return $this->get('authManager', false);
  548. }
  549. /**
  550. * Returns the asset manager.
  551. * @return \yii\web\AssetManager the asset manager application component.
  552. */
  553. public function getAssetManager()
  554. {
  555. return $this->get('assetManager');
  556. }
  557. /**
  558. * Returns the security component.
  559. * @return \yii\base\Security the security application component.
  560. */
  561. public function getSecurity()
  562. {
  563. return $this->get('security');
  564. }
  565. /**
  566. * Returns the configuration of core application components.
  567. * @return array
  568. * @see set()
  569. */
  570. public function coreComponents()
  571. {
  572. $components = [
  573. 'log' => ['class' => 'yii\log\Dispatcher'],
  574. 'view' => ['class' => 'yii\web\View'],
  575. 'formatter' => ['class' => 'yii\i18n\Formatter'],
  576. 'i18n' => ['class' => 'yii\i18n\I18N'],
  577. 'urlManager' => ['class' => 'yii\web\UrlManager'],
  578. 'assetManager' => ['class' => 'yii\web\AssetManager'],
  579. 'security' => ['class' => 'yii\base\Security'],
  580. ];
  581. if (class_exists('yii\swiftmailer\Mailer')) {
  582. $components['mailer'] = ['class' => 'yii\swiftmailer\Mailer'];
  583. }
  584. return $components;
  585. }
  586. /**
  587. * Terminates the application.
  588. * This method replaces the `exit()` function by ensuring the application life cycle is completed
  589. * before terminating the application.
  590. * @param int $status the exit status (value 0 means normal exit while other values mean abnormal exit).
  591. * @param Response|null $response the response to be sent. If not set, the default application [[response]] component will be used.
  592. * @throws ExitException if the application is in testing mode
  593. */
  594. public function end($status = 0, $response = null)
  595. {
  596. if ($this->state === self::STATE_BEFORE_REQUEST || $this->state === self::STATE_HANDLING_REQUEST) {
  597. $this->state = self::STATE_AFTER_REQUEST;
  598. $this->trigger(self::EVENT_AFTER_REQUEST);
  599. }
  600. if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) {
  601. $this->state = self::STATE_END;
  602. $response = $response ?: $this->getResponse();
  603. $response->send();
  604. }
  605. if (YII_ENV_TEST) {
  606. throw new ExitException($status);
  607. }
  608. exit($status);
  609. }
  610. /**
  611. * Configures [[Yii::$container]] with the $config.
  612. *
  613. * @param array $config values given in terms of name-value pairs
  614. * @since 2.0.11
  615. */
  616. public function setContainer($config)
  617. {
  618. Yii::configure(Yii::$container, $config);
  619. }
  620. }