HelpController.php 12 KB
Newer Older
Alexander Makarov committed
1 2
<?php
/**
Qiang Xue committed
3
 * HelpController class file.
Alexander Makarov committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Alexander Makarov committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

10
namespace yii\console\controllers;
Alexander Makarov committed
11

12
use Yii;
Qiang Xue committed
13
use yii\base\Application;
Qiang Xue committed
14
use yii\console\Exception;
Qiang Xue committed
15 16
use yii\base\InlineAction;
use yii\console\Controller;
Qiang Xue committed
17
use yii\console\Request;
Qiang Xue committed
18
use yii\util\StringHelper;
Qiang Xue committed
19

Alexander Makarov committed
20
/**
Qiang Xue committed
21
 * This command provides help information about console commands.
Alexander Makarov committed
22
 *
Qiang Xue committed
23 24 25
 * This command displays the available command list in
 * the application or the detailed instructions about using
 * a specific command.
Alexander Makarov committed
26
 *
Qiang Xue committed
27
 * This command can be used as follows on command line:
Qiang Xue committed
28 29 30 31 32
 *
 * ~~~
 * yiic help [command name]
 * ~~~
 *
Qiang Xue committed
33 34
 * In the above, if the command name is not provided, all
 * available commands will be displayed.
Alexander Makarov committed
35 36 37 38
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
39
class HelpController extends Controller
Alexander Makarov committed
40
{
Qiang Xue committed
41 42 43 44 45 46 47 48 49
	/**
	 * Displays available commands or the detailed information
	 * about a particular command. For example,
	 *
	 * ~~~
	 * yiic help          # list available commands
	 * yiic help message  # display help info about "message"
	 * ~~~
	 *
Qiang Xue committed
50
	 * @param string $command The name of the command to show help about.
Qiang Xue committed
51
	 * If not provided, all available commands will be displayed.
Qiang Xue committed
52
	 * @return integer the exit status
Qiang Xue committed
53
	 * @throws Exception if the command for help is unknown
Qiang Xue committed
54
	 */
Qiang Xue committed
55
	public function actionIndex($command = null)
Qiang Xue committed
56
	{
Qiang Xue committed
57 58
		if ($command !== null) {
			$result = Yii::$application->createController($command);
Qiang Xue committed
59
			if ($result === false) {
Qiang Xue committed
60
				throw new Exception(Yii::t('yii', 'No help for unknown command "{command}".', array(
Qiang Xue committed
61
					'{command}' => $command,
62
				)));
Qiang Xue committed
63 64
			}

Qiang Xue committed
65
			list($controller, $actionID) = $result;
Qiang Xue committed
66

Qiang Xue committed
67 68
			$actions = $this->getActions($controller);
			if ($actionID !== '' || count($actions) === 1 && $actions[0] === $controller->defaultAction) {
69
				$this->getActionHelp($controller, $actionID);
Qiang Xue committed
70 71
			} else {
				$this->getControllerHelp($controller);
Qiang Xue committed
72
			}
Qiang Xue committed
73 74
		} else {
			$this->getHelp();
Qiang Xue committed
75 76 77 78 79 80 81 82 83
		}
	}

	/**
	 * Returns all available command names.
	 * @return array all available command names
	 */
	public function getCommands()
	{
84
		$commands = $this->getModuleCommands(Yii::$application);
Qiang Xue committed
85 86 87 88 89 90 91 92 93 94 95
		sort($commands);
		return array_unique($commands);
	}

	/**
	 * Returns all available actions of the specified controller.
	 * @param Controller $controller the controller instance
	 * @return array all available action IDs.
	 */
	public function getActions($controller)
	{
Qiang Xue committed
96
		$actions = array_keys($controller->actions());
Qiang Xue committed
97 98 99
		$class = new \ReflectionClass($controller);
		foreach ($class->getMethods() as $method) {
			$name = $method->getName();
Qiang Xue committed
100 101
			if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0 && $name !== 'actions') {
				$actions[] = StringHelper::camel2id(substr($name, 6));
Qiang Xue committed
102 103 104 105 106 107 108 109 110 111 112 113 114
			}
		}
		sort($actions);
		return array_unique($actions);
	}

	/**
	 * Returns available commands of a specified module.
	 * @param \yii\base\Module $module the module instance
	 * @return array the available command names
	 */
	protected function getModuleCommands($module)
	{
Qiang Xue committed
115
		$prefix = $module instanceof Application ? '' : $module->getUniqueID() . '/';
Qiang Xue committed
116 117

		$commands = array();
Qiang Xue committed
118
		foreach (array_keys($module->controllerMap) as $id) {
Qiang Xue committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
			$commands[] = $prefix . $id;
		}

		foreach ($module->getModules() as $id => $child) {
			if (($child = $module->getModule($id)) === null) {
				continue;
			}
			foreach ($this->getModuleCommands($child) as $command) {
				$commands[] = $prefix . $id . '/' . $command;
			}
		}

		$files = scandir($module->getControllerPath());
		foreach ($files as $file) {
			if(strcmp(substr($file,-14),'Controller.php') === 0 && is_file($file)) {
				$commands[] = $prefix . lcfirst(substr(basename($file), 0, -14));
			}
		}

		return $commands;
	}

	/**
	 * Displays all available commands.
	 */
Qiang Xue committed
144
	protected function getHelp()
Qiang Xue committed
145
	{
Qiang Xue committed
146 147
		$commands = $this->getCommands();
		if ($commands !== array()) {
Qiang Xue committed
148
			echo "The following commands are available:\n\n";
Qiang Xue committed
149
			foreach ($commands as $command) {
Qiang Xue committed
150
				echo "* $command\n";
Qiang Xue committed
151
			}
Qiang Xue committed
152
			echo "\nTo see the help of each command, enter:\n";
Qiang Xue committed
153
			echo "\n  yiic help <command-name>\n\n";
Qiang Xue committed
154 155 156 157
		} else {
			echo "\nNo commands are found.\n";
		}
	}
Qiang Xue committed
158

Qiang Xue committed
159 160 161 162
	/**
	 * Displays the overall information of the command.
	 * @param Controller $controller the controller instance
	 */
Qiang Xue committed
163
	protected function getControllerHelp($controller)
Qiang Xue committed
164
	{
Qiang Xue committed
165 166 167 168 169 170 171
		$class = new \ReflectionClass($controller);
		$comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($class->getDocComment(), '/'))), "\r", '');
		if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
			$comment = trim(substr($comment, 0, $matches[0][1]));
		}

		if ($comment !== '') {
Qiang Xue committed
172 173
			echo "\nDESCRIPTION\n";
			echo "\n" . $comment . "\n\n";
Qiang Xue committed
174 175 176 177
		}

		$actions = $this->getActions($controller);
		if ($actions !== array()) {
Qiang Xue committed
178
			echo "\nSUB-COMMANDS\n\n";
Qiang Xue committed
179 180
			$prefix = $controller->getUniqueId();
			foreach ($actions as $action) {
Qiang Xue committed
181
				if ($action === $controller->defaultAction) {
Qiang Xue committed
182
					echo "* $prefix/$action (default)";
Qiang Xue committed
183
				} else {
Qiang Xue committed
184
					echo "* $prefix/$action";
Qiang Xue committed
185
				}
Qiang Xue committed
186 187 188 189 190
				$summary = $this->getActionSummary($controller, $action);
				if ($summary !== '') {
					echo ': ' . $summary;
				}
				echo "\n";
Qiang Xue committed
191
			}
Qiang Xue committed
192
			echo "\n\nTo see the detailed information about individual sub-commands, enter:\n";
Qiang Xue committed
193
			echo "\n  yiic help <sub-command>\n\n";
Qiang Xue committed
194
		}
Qiang Xue committed
195 196
	}

Qiang Xue committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	/**
	 * Returns the short summary of the action.
	 * @param Controller $controller the controller instance
	 * @param string $actionID action ID
	 * @return string the summary about the action
	 */
	protected function getActionSummary($controller, $actionID)
	{
		$action = $controller->createAction($actionID);
		if ($action === null) {
			return '';
		}
		if ($action instanceof InlineAction) {
			$reflection = new \ReflectionMethod($controller, $action->actionMethod);
		} else {
			$reflection = new \ReflectionClass($action);
		}
		$tags = $this->parseComment($reflection->getDocComment());
		if ($tags['description'] !== '') {
			$limit = 73 - strlen($action->getUniqueId());
			if ($actionID === $controller->defaultAction) {
				$limit -= 10;
			}
			if ($limit < 0) {
				$limit = 50;
			}
			$description = $tags['description'];
			if (($pos = strpos($tags['description'], "\n")) !== false) {
				$description = substr($description, 0, $pos);
			}
			$text = substr($description, 0, $limit);
			return strlen($description) > $limit ? $text . '...' : $text;
		} else {
			return '';
		}
	}

Alexander Makarov committed
234
	/**
Qiang Xue committed
235 236 237
	 * Displays the detailed information of a command action.
	 * @param Controller $controller the controller instance
	 * @param string $actionID action ID
Qiang Xue committed
238
	 * @throws Exception if the action does not exist
Alexander Makarov committed
239
	 */
Qiang Xue committed
240
	protected function getActionHelp($controller, $actionID)
Alexander Makarov committed
241
	{
Qiang Xue committed
242 243
		$action = $controller->createAction($actionID);
		if ($action === null) {
Qiang Xue committed
244
			throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', array(
Qiang Xue committed
245
				'{command}' => rtrim($controller->getUniqueId() . '/' . $actionID, '/'),
246
			)));
Qiang Xue committed
247 248
		}
		if ($action instanceof InlineAction) {
Qiang Xue committed
249
			$method = new \ReflectionMethod($controller, $action->actionMethod);
Qiang Xue committed
250 251 252
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}
Qiang Xue committed
253 254

		$tags = $this->parseComment($method->getDocComment());
Qiang Xue committed
255 256 257 258 259

		if ($tags['description'] !== '') {
			echo "\nDESCRIPTION";
			echo "\n\n" . $tags['description'] . "\n\n";
		}
Qiang Xue committed
260 261 262 263

		echo "\nUSAGE\n\n";
		if ($action->id === $controller->defaultAction) {
			echo 'yiic ' . $controller->getUniqueId();
Qiang Xue committed
264
		} else {
Qiang Xue committed
265 266
			echo "yiic " . $action->getUniqueId();
		}
Qiang Xue committed
267 268 269
		list ($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : array());
		if (!empty($required)) {
			echo ' <' . implode('> <', array_keys($required)) . '>';
Alexander Makarov committed
270
		}
Qiang Xue committed
271 272
		if (!empty($optional)) {
			echo ' [' . implode('] [', array_keys($optional)) . ']';
Qiang Xue committed
273
		}
Qiang Xue committed
274
		echo "\n\n";
Qiang Xue committed
275

Qiang Xue committed
276 277
		if (!empty($required) || !empty($optional)) {
			echo implode("\n\n", array_merge($required, $optional)) . "\n\n";
Qiang Xue committed
278
		}
Qiang Xue committed
279

Qiang Xue committed
280
		$options = $this->getOptionHelps($controller);
Qiang Xue committed
281
		if ($options !== array()) {
Qiang Xue committed
282 283 284 285 286
			echo "\nOPTIONS\n\n";
			echo implode("\n\n", $options) . "\n\n";
		}
	}

Qiang Xue committed
287
	/**
Qiang Xue committed
288
	 * Returns the help information about arguments.
Qiang Xue committed
289
	 * @param \ReflectionMethod $method
Qiang Xue committed
290 291
	 * @param string $tags the parsed comment block related with arguments
	 * @return array the required and optional argument help information
Qiang Xue committed
292
	 */
Qiang Xue committed
293
	protected function getArgHelps($method, $tags)
Qiang Xue committed
294
	{
Qiang Xue committed
295 296 297
		if (is_string($tags)) {
			$tags = array($tags);
		}
Qiang Xue committed
298
		$params = $method->getParameters();
Qiang Xue committed
299 300 301 302 303 304 305 306 307 308 309 310
		$optional = $required = array();
		foreach ($params as $i => $param) {
			$name = $param->getName();
			$tag = isset($tags[$i]) ? $tags[$i] : '';
			if (preg_match('/^([^\s]+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
				$type = $matches[1];
				$comment = $matches[3];
			} else {
				$type = null;
				$comment = $tag;
			}
			if ($param->isDefaultValueAvailable()) {
Qiang Xue committed
311
				$optional[$name] = $this->formatOptionHelp('* ' . $name, false, $type, $param->getDefaultValue(), $comment);
Qiang Xue committed
312
			} else {
Qiang Xue committed
313
				$required[$name] = $this->formatOptionHelp('* ' . $name, true, $type, null, $comment);
Qiang Xue committed
314 315
			}
		}
Qiang Xue committed
316

Qiang Xue committed
317
		return array($required, $optional);
Qiang Xue committed
318 319 320
	}

	/**
Qiang Xue committed
321 322 323
	 * Returns the help information about the options available for a console controller.
	 * @param Controller $controller the console controller
	 * @return array the help information about the options
Qiang Xue committed
324
	 */
Qiang Xue committed
325
	protected function getOptionHelps($controller)
Qiang Xue committed
326
	{
Qiang Xue committed
327 328 329 330 331 332
		$optionNames = $controller->globalOptions();
		if (empty($optionNames)) {
			return array();
		}

		$class = new \ReflectionClass($controller);
Qiang Xue committed
333 334 335
		$options = array();
		foreach ($class->getProperties() as $property) {
			$name = $property->getName();
Qiang Xue committed
336 337
			if (!in_array($name, $optionNames, true)) {
				continue;
Qiang Xue committed
338
			}
Qiang Xue committed
339 340 341 342 343 344
			$defaultValue = $property->getValue($controller);
			$tags = $this->parseComment($property->getDocComment());
			if (isset($tags['var']) || isset($tags['property'])) {
				$doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
				if (is_array($doc)) {
					$doc = reset($doc);
Qiang Xue committed
345
				}
Qiang Xue committed
346 347 348 349 350 351 352
				if (preg_match('/^([^\s]+)(.*)/s', $doc, $matches)) {
					$type = $matches[1];
					$comment = $matches[2];
				} else {
					$type = null;
					$comment = $doc;
				}
Qiang Xue committed
353
				$options[$name] = $this->formatOptionHelp('--' . $name, false, $type, $defaultValue, $comment);
Qiang Xue committed
354
			} else {
Qiang Xue committed
355
				$options[$name] = $this->formatOptionHelp('--' . $name, false, null, $defaultValue, '');
Qiang Xue committed
356 357 358 359
			}
		}
		ksort($options);
		return $options;
Alexander Makarov committed
360
	}
Qiang Xue committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

	/**
	 * Parses the comment block into tags.
	 * @param string $comment the comment block
	 * @return array the parsed tags
	 */
	protected function parseComment($comment)
	{
		$tags = array();
		$comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
		$parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
		foreach ($parts as $part) {
			if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
				$name = $matches[1];
				if (!isset($tags[$name])) {
					$tags[$name] = trim($matches[2]);
				} elseif (is_array($tags[$name])) {
					$tags[$name][] = trim($matches[2]);
				} else {
					$tags[$name] = array($tags[$name], trim($matches[2]));
				}
			}
		}
		return $tags;
	}

	/**
	 * Generates a well-formed string for an argument or option.
	 * @param string $name the name of the argument or option
	 * @param boolean $required whether the argument is required
	 * @param string $type the type of the option or argument
	 * @param mixed $defaultValue the default value of the option or argument
	 * @param string $comment comment about the option or argument
	 * @return string the formatted string for the argument or option
	 */
	protected function formatOptionHelp($name, $required, $type, $defaultValue, $comment)
	{
		$doc = '';
		$comment = trim($comment);

		if ($defaultValue !== null && !is_array($defaultValue)) {
			if ($type === null) {
				$type = gettype($defaultValue);
			}
			$doc = "$type (defaults to " . var_export($defaultValue, true) . ")";
		} elseif (trim($type) !== '') {
			$doc = $type;
		}

		if ($doc === '') {
			$doc = $comment;
		} elseif ($comment !== '') {
			$doc .= "\n" . preg_replace("/^/m", "  ", $comment);
		}

		$name = $required ? "$name (required)" : $name;
		return $doc === '' ? $name : "$name: $doc";
	}
Alexander Makarov committed
419
}