Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

243 lines
8.3KB

  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. // http://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 ErrorHandler $errorHandler The error handler application component. This property is read-only.
  50. * @property Request $request The request component. This property is read-only.
  51. * @property Response $response The response component. This property is read-only.
  52. *
  53. * @author Qiang Xue <qiang.xue@gmail.com>
  54. * @since 2.0
  55. */
  56. class Application extends \yii\base\Application
  57. {
  58. /**
  59. * The option name for specifying the application configuration file path.
  60. */
  61. const OPTION_APPCONFIG = 'appconfig';
  62. /**
  63. * @var string the default route of this application. Defaults to 'help',
  64. * meaning the `help` command.
  65. */
  66. public $defaultRoute = 'help';
  67. /**
  68. * @var boolean whether to enable the commands provided by the core framework.
  69. * Defaults to true.
  70. */
  71. public $enableCoreCommands = true;
  72. /**
  73. * @var Controller the currently active controller instance
  74. */
  75. public $controller;
  76. /**
  77. * @inheritdoc
  78. */
  79. public function __construct($config = [])
  80. {
  81. $config = $this->loadConfig($config);
  82. parent::__construct($config);
  83. }
  84. /**
  85. * Loads the configuration.
  86. * This method will check if the command line option [[OPTION_APPCONFIG]] is specified.
  87. * If so, the corresponding file will be loaded as the application configuration.
  88. * Otherwise, the configuration provided as the parameter will be returned back.
  89. * @param array $config the configuration provided in the constructor.
  90. * @return array the actual configuration to be used by the application.
  91. */
  92. protected function loadConfig($config)
  93. {
  94. if (!empty($_SERVER['argv'])) {
  95. $option = '--' . self::OPTION_APPCONFIG . '=';
  96. foreach ($_SERVER['argv'] as $param) {
  97. if (strpos($param, $option) !== false) {
  98. $path = substr($param, strlen($option));
  99. if (!empty($path) && is_file($file = Yii::getAlias($path))) {
  100. return require($file);
  101. } else {
  102. exit("The configuration file does not exist: $path\n");
  103. }
  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. } else {
  140. $response = $this->getResponse();
  141. $response->exitStatus = $result;
  142. return $response;
  143. }
  144. }
  145. /**
  146. * Runs a controller action specified by a route.
  147. * This method parses the specified route and creates the corresponding child module(s), controller and action
  148. * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
  149. * If the route is empty, the method will use [[defaultRoute]].
  150. *
  151. * For example, to run `public function actionTest($a, $b)` assuming that the controller has options the following
  152. * code should be used:
  153. *
  154. * ```php
  155. * \Yii::$app->runAction('controller/test', ['option' => 'value', $a, $b]);
  156. * ```
  157. *
  158. * @param string $route the route that specifies the action.
  159. * @param array $params the parameters to be passed to the action
  160. * @return integer|Response the result of the action. This can be either an exit code or Response object.
  161. * Exit code 0 means normal, and other values mean abnormal. Exit code of `null` is treaded as `0` as well.
  162. * @throws Exception if the route is invalid
  163. */
  164. public function runAction($route, $params = [])
  165. {
  166. try {
  167. $res = parent::runAction($route, $params);
  168. return is_object($res) ? $res : (int)$res;
  169. } catch (InvalidRouteException $e) {
  170. throw new Exception("Unknown command \"$route\".", 0, $e);
  171. }
  172. }
  173. /**
  174. * Returns the configuration of the built-in commands.
  175. * @return array the configuration of the built-in commands.
  176. */
  177. public function coreCommands()
  178. {
  179. return [
  180. 'asset' => 'yii\console\controllers\AssetController',
  181. 'cache' => 'yii\console\controllers\CacheController',
  182. 'fixture' => 'yii\console\controllers\FixtureController',
  183. 'help' => 'yii\console\controllers\HelpController',
  184. 'message' => 'yii\console\controllers\MessageController',
  185. 'migrate' => 'yii\console\controllers\MigrateController',
  186. 'serve' => 'yii\console\controllers\ServeController',
  187. ];
  188. }
  189. /**
  190. * Returns the error handler component.
  191. * @return ErrorHandler the error handler application component.
  192. */
  193. public function getErrorHandler()
  194. {
  195. return $this->get('errorHandler');
  196. }
  197. /**
  198. * Returns the request component.
  199. * @return Request the request component.
  200. */
  201. public function getRequest()
  202. {
  203. return $this->get('request');
  204. }
  205. /**
  206. * Returns the response component.
  207. * @return Response the response component.
  208. */
  209. public function getResponse()
  210. {
  211. return $this->get('response');
  212. }
  213. /**
  214. * @inheritdoc
  215. */
  216. public function coreComponents()
  217. {
  218. return array_merge(parent::coreComponents(), [
  219. 'request' => ['class' => 'yii\console\Request'],
  220. 'response' => ['class' => 'yii\console\Response'],
  221. 'errorHandler' => ['class' => 'yii\console\ErrorHandler'],
  222. ]);
  223. }
  224. }