Application.php 6.27 KB
Newer Older
Alexander Makarov committed
1 2 3 4 5
<?php
/**
 * Console Application class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright (c) 2008 Yii Software LLC
Alexander Makarov committed
7 8 9 10 11
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console;

12
use Yii;
Qiang Xue committed
13
use yii\base\InvalidRouteException;
Qiang Xue committed
14

Alexander Makarov committed
15
/**
Qiang Xue committed
16
 * Application represents a console application.
Alexander Makarov committed
17
 *
Carsten Brandt committed
18
 * Application extends from [[\yii\base\Application]] by providing functionalities that are
Alexander Makarov committed
19 20 21
 * specific to console requests. In particular, it deals with console requests
 * through a command-based approach:
 *
Qiang Xue committed
22
 * - A console application consists of one or several possible user commands;
Qiang Xue committed
23
 * - Each user command is implemented as a class extending [[\yii\console\Controller]];
Qiang Xue committed
24 25 26
 * - User specifies which command to run on the command line;
 * - The command processes the user request with the specified parameters.
 *
Qiang Xue committed
27
 * The command classes reside in the directory specified by [[controllerPath]].
Qiang Xue committed
28
 * Their naming should follow the same naming convention as controllers. For example, the `help` command
Qiang Xue committed
29
 * is implemented using the `HelpController` class.
Alexander Makarov committed
30 31 32
 *
 * To run the console application, enter the following on the command line:
 *
Qiang Xue committed
33
 * ~~~
34
 * yii <route> [--param1=value1 --param2 ...]
Qiang Xue committed
35 36
 * ~~~
 *
Qiang Xue committed
37
 * where `<route>` refers to a controller route in the form of `ModuleID/ControllerID/ActionID`
Qiang Xue committed
38 39 40
 * (e.g. `sitemap/create`), and `param1`, `param2` refers to a set of named parameters that
 * will be used to initialize the controller action (e.g. `--since=0` specifies a `since` parameter
 * whose value is 0 and a corresponding `$since` parameter is passed to the action method).
Qiang Xue committed
41
 *
Qiang Xue committed
42
 * A `help` command is provided by default, which lists available commands and shows their usage.
Qiang Xue committed
43
 * To use this command, simply type:
Qiang Xue committed
44 45
 *
 * ~~~
46
 * yii help
Qiang Xue committed
47
 * ~~~
Alexander Makarov committed
48
 *
49
 * @property Response $response The response component. This property is read-only.
50
 *
Alexander Makarov committed
51 52 53 54 55
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Application extends \yii\base\Application
{
56 57 58 59 60
	/**
	 * The option name for specifying the application configuration file path.
	 */
	const OPTION_APPCONFIG = 'appconfig';

Alexander Makarov committed
61
	/**
Qiang Xue committed
62 63
	 * @var string the default route of this application. Defaults to 'help',
	 * meaning the `help` command.
Alexander Makarov committed
64
	 */
Qiang Xue committed
65
	public $defaultRoute = 'help';
Alexander Makarov committed
66
	/**
Qiang Xue committed
67 68
	 * @var boolean whether to enable the commands provided by the core framework.
	 * Defaults to true.
Alexander Makarov committed
69
	 */
Qiang Xue committed
70
	public $enableCoreCommands = true;
71 72 73 74
	/**
	 * @var Controller the currently active controller instance
	 */
	public $controller;
Alexander Makarov committed
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

	/**
	 * @inheritdoc
	 */
	public function __construct($config = [])
	{
		$config = $this->loadConfig($config);
		parent::__construct($config);
	}

	/**
	 * Loads the configuration.
	 * This method will check if the command line option [[OPTION_APPCONFIG]] is specified.
	 * If so, the corresponding file will be loaded as the application configuration.
	 * Otherwise, the configuration provided as the parameter will be returned back.
	 * @param array $config the configuration provided in the constructor.
	 * @return array the actual configuration to be used by the application.
	 */
	protected function loadConfig($config)
	{
		if (!empty($_SERVER['argv'])) {
			$option = '--' . self::OPTION_APPCONFIG . '=';
			foreach ($_SERVER['argv'] as $param) {
				if (strpos($param, $option) !== false) {
					$path = substr($param, strlen($option));
101 102
					if (!empty($path) && is_file($file = Yii::getAlias($path))) {
						return require($file);
103 104 105 106 107 108 109 110 111
					} else {
						die("The configuration file does not exist: $path\n");
					}
				}
			}
		}
		return $config;
	}

112 113 114
	/**
	 * Initialize the application.
	 */
Alexander Makarov committed
115 116
	public function init()
	{
Qiang Xue committed
117 118 119
		parent::init();
		if ($this->enableCoreCommands) {
			foreach ($this->coreCommands() as $id => $command) {
Qiang Xue committed
120 121
				if (!isset($this->controllerMap[$id])) {
					$this->controllerMap[$id] = $command;
Qiang Xue committed
122 123 124 125
				}
			}
		}
		// ensure we have the 'help' command so that we can list the available commands
Qiang Xue committed
126 127
		if (!isset($this->controllerMap['help'])) {
			$this->controllerMap['help'] = 'yii\console\controllers\HelpController';
Alexander Makarov committed
128 129 130
		}
	}

131 132 133 134 135
	/**
	 * Handles the specified request.
	 * @param Request $request the request to be handled
	 * @return Response the resulting response
	 */
136
	public function handleRequest($request)
137 138
	{
		list ($route, $params) = $request->resolve();
Qiang Xue committed
139
		$this->requestedRoute = $route;
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
		$result = $this->runAction($route, $params);
		if ($result instanceof Response) {
			return $result;
		} else {
			$response = $this->getResponse();
			$response->exitStatus = (int)$result;
			return $response;
		}
	}

	/**
	 * Returns the response component.
	 * @return Response the response component
	 */
	public function getResponse()
	{
		return $this->getComponent('response');
	}

	/**
	 * Runs a controller action specified by a route.
	 * This method parses the specified route and creates the corresponding child module(s), controller and action
	 * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
	 * If the route is empty, the method will use [[defaultRoute]].
	 * @param string $route the route that specifies the action.
	 * @param array $params the parameters to be passed to the action
	 * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
	 * @throws Exception if the route is invalid
	 */
Alexander Makarov committed
169
	public function runAction($route, $params = [])
170
	{
Qiang Xue committed
171
		try {
172
			return parent::runAction($route, $params);
Qiang Xue committed
173
		} catch (InvalidRouteException $e) {
Alexander Makarov committed
174
			throw new Exception(Yii::t('yii', 'Unknown command "{command}".', ['command' => $route]), 0, $e);
Qiang Xue committed
175
		}
Qiang Xue committed
176 177
	}

178 179 180 181
	/**
	 * Returns the configuration of the built-in commands.
	 * @return array the configuration of the built-in commands.
	 */
Qiang Xue committed
182
	public function coreCommands()
Alexander Makarov committed
183
	{
Alexander Makarov committed
184
		return [
185 186 187
			'message' => 'yii\console\controllers\MessageController',
			'help' => 'yii\console\controllers\HelpController',
			'migrate' => 'yii\console\controllers\MigrateController',
188
			'cache' => 'yii\console\controllers\CacheController',
189
			'asset' => 'yii\console\controllers\AssetController',
190
			'fixture' => 'yii\console\controllers\FixtureController',
Alexander Makarov committed
191
		];
Alexander Makarov committed
192
	}
Qiang Xue committed
193 194 195 196 197 198 199 200

	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
	public function registerCoreComponents()
	{
		parent::registerCoreComponents();
Alexander Makarov committed
201 202 203 204
		$this->setComponents([
			'request' => ['class' => 'yii\console\Request'],
			'response' => ['class' => 'yii\console\Response'],
		]);
Qiang Xue committed
205
	}
Alexander Makarov committed
206
}