Application.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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\console;
  8. use Yii;
  9. use yii\base\InvalidRouteException;
  10. // define STDIN, STDOUT and STDERR if the PHP SAPI did not define them (e.g. creating console application in web env)
  11. // https://secure.php.net/manual/en/features.commandline.io-streams.php
  12. defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
  13. defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
  14. defined('STDERR') or define('STDERR', fopen('php://stderr', 'w'));
  15. /**
  16. * Application represents a console application.
  17. *
  18. * Application extends from [[\yii\base\Application]] by providing functionalities that are
  19. * specific to console requests. In particular, it deals with console requests
  20. * through a command-based approach:
  21. *
  22. * - A console application consists of one or several possible user commands;
  23. * - Each user command is implemented as a class extending [[\yii\console\Controller]];
  24. * - User specifies which command to run on the command line;
  25. * - The command processes the user request with the specified parameters.
  26. *
  27. * The command classes should be under the namespace specified by [[controllerNamespace]].
  28. * Their naming should follow the same naming convention as controllers. For example, the `help` command
  29. * is implemented using the `HelpController` class.
  30. *
  31. * To run the console application, enter the following on the command line:
  32. *
  33. * ```
  34. * yii <route> [--param1=value1 --param2 ...]
  35. * ```
  36. *
  37. * where `<route>` refers to a controller route in the form of `ModuleID/ControllerID/ActionID`
  38. * (e.g. `sitemap/create`), and `param1`, `param2` refers to a set of named parameters that
  39. * will be used to initialize the controller action (e.g. `--since=0` specifies a `since` parameter
  40. * whose value is 0 and a corresponding `$since` parameter is passed to the action method).
  41. *
  42. * A `help` command is provided by default, which lists available commands and shows their usage.
  43. * To use this command, simply type:
  44. *
  45. * ```
  46. * yii help
  47. * ```
  48. *
  49. * @property-read ErrorHandler $errorHandler The error handler application component. This property is
  50. * read-only.
  51. * @property-read Request $request The request component. This property is read-only.
  52. * @property-read Response $response The response component. This property is read-only.
  53. *
  54. * @author Qiang Xue <qiang.xue@gmail.com>
  55. * @since 2.0
  56. */
  57. class Application extends \yii\base\Application
  58. {
  59. /**
  60. * The option name for specifying the application configuration file path.
  61. */
  62. const OPTION_APPCONFIG = 'appconfig';
  63. /**
  64. * @var string the default route of this application. Defaults to 'help',
  65. * meaning the `help` command.
  66. */
  67. public $defaultRoute = 'help';
  68. /**
  69. * @var bool whether to enable the commands provided by the core framework.
  70. * Defaults to true.
  71. */
  72. public $enableCoreCommands = true;
  73. /**
  74. * @var Controller the currently active controller instance
  75. */
  76. public $controller;
  77. /**
  78. * {@inheritdoc}
  79. */
  80. public function __construct($config = [])
  81. {
  82. $config = $this->loadConfig($config);
  83. parent::__construct($config);
  84. }
  85. /**
  86. * Loads the configuration.
  87. * This method will check if the command line option [[OPTION_APPCONFIG]] is specified.
  88. * If so, the corresponding file will be loaded as the application configuration.
  89. * Otherwise, the configuration provided as the parameter will be returned back.
  90. * @param array $config the configuration provided in the constructor.
  91. * @return array the actual configuration to be used by the application.
  92. */
  93. protected function loadConfig($config)
  94. {
  95. if (!empty($_SERVER['argv'])) {
  96. $option = '--' . self::OPTION_APPCONFIG . '=';
  97. foreach ($_SERVER['argv'] as $param) {
  98. if (strpos($param, $option) !== false) {
  99. $path = substr($param, strlen($option));
  100. if (!empty($path) && is_file($file = Yii::getAlias($path))) {
  101. return require $file;
  102. }
  103. exit("The configuration file does not exist: $path\n");
  104. }
  105. }
  106. }
  107. return $config;
  108. }
  109. /**
  110. * Initialize the application.
  111. */
  112. public function init()
  113. {
  114. parent::init();
  115. if ($this->enableCoreCommands) {
  116. foreach ($this->coreCommands() as $id => $command) {
  117. if (!isset($this->controllerMap[$id])) {
  118. $this->controllerMap[$id] = $command;
  119. }
  120. }
  121. }
  122. // ensure we have the 'help' command so that we can list the available commands
  123. if (!isset($this->controllerMap['help'])) {
  124. $this->controllerMap['help'] = 'yii\console\controllers\HelpController';
  125. }
  126. }
  127. /**
  128. * Handles the specified request.
  129. * @param Request $request the request to be handled
  130. * @return Response the resulting response
  131. */
  132. public function handleRequest($request)
  133. {
  134. list($route, $params) = $request->resolve();
  135. $this->requestedRoute = $route;
  136. $result = $this->runAction($route, $params);
  137. if ($result instanceof Response) {
  138. return $result;
  139. }
  140. $response = $this->getResponse();
  141. $response->exitStatus = $result;
  142. return $response;
  143. }
  144. /**
  145. * Runs a controller action specified by a route.
  146. * This method parses the specified route and creates the corresponding child module(s), controller and action
  147. * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
  148. * If the route is empty, the method will use [[defaultRoute]].
  149. *
  150. * For example, to run `public function actionTest($a, $b)` assuming that the controller has options the following
  151. * code should be used:
  152. *
  153. * ```php
  154. * \Yii::$app->runAction('controller/test', ['option' => 'value', $a, $b]);
  155. * ```
  156. *
  157. * @param string $route the route that specifies the action.
  158. * @param array $params the parameters to be passed to the action
  159. * @return int|Response the result of the action. This can be either an exit code or Response object.
  160. * Exit code 0 means normal, and other values mean abnormal. Exit code of `null` is treaded as `0` as well.
  161. * @throws Exception if the route is invalid
  162. */
  163. public function runAction($route, $params = [])
  164. {
  165. try {
  166. $res = parent::runAction($route, $params);
  167. return is_object($res) ? $res : (int) $res;
  168. } catch (InvalidRouteException $e) {
  169. throw new UnknownCommandException($route, $this, 0, $e);
  170. }
  171. }
  172. /**
  173. * Returns the configuration of the built-in commands.
  174. * @return array the configuration of the built-in commands.
  175. */
  176. public function coreCommands()
  177. {
  178. return [
  179. 'asset' => 'yii\console\controllers\AssetController',
  180. 'cache' => 'yii\console\controllers\CacheController',
  181. 'fixture' => 'yii\console\controllers\FixtureController',
  182. 'help' => 'yii\console\controllers\HelpController',
  183. 'message' => 'yii\console\controllers\MessageController',
  184. 'migrate' => 'yii\console\controllers\MigrateController',
  185. 'serve' => 'yii\console\controllers\ServeController',
  186. ];
  187. }
  188. /**
  189. * Returns the error handler component.
  190. * @return ErrorHandler the error handler application component.
  191. */
  192. public function getErrorHandler()
  193. {
  194. return $this->get('errorHandler');
  195. }
  196. /**
  197. * Returns the request component.
  198. * @return Request the request component.
  199. */
  200. public function getRequest()
  201. {
  202. return $this->get('request');
  203. }
  204. /**
  205. * Returns the response component.
  206. * @return Response the response component.
  207. */
  208. public function getResponse()
  209. {
  210. return $this->get('response');
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function coreComponents()
  216. {
  217. return array_merge(parent::coreComponents(), [
  218. 'request' => ['class' => 'yii\console\Request'],
  219. 'response' => ['class' => 'yii\console\Response'],
  220. 'errorHandler' => ['class' => 'yii\console\ErrorHandler'],
  221. ]);
  222. }
  223. }