HelpController.php 16.9 KB
Newer Older
Alexander Makarov committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Alexander Makarov committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\console\controllers;
Alexander Makarov committed
9

10
use Yii;
Qiang Xue committed
11
use yii\base\Application;
12
use yii\base\InlineAction;
Carsten Brandt committed
13
use yii\console\Action;
Qiang Xue committed
14
use yii\console\Controller;
Qiang Xue committed
15
use yii\console\Exception;
16
use yii\helpers\Console;
Alexander Makarov committed
17
use yii\helpers\Inflector;
Qiang Xue committed
18

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

            list($controller, $actionID) = $result;

            $actions = $this->getActions($controller);
            if ($actionID !== '' || count($actions) === 1 && $actions[0] === $controller->defaultAction) {
65
                $this->getControllerActionHelp($controller, $actionID);
66 67 68 69
            } else {
                $this->getControllerHelp($controller);
            }
        } else {
Carsten Brandt committed
70
            $this->getGlobalHelp();
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        }
    }

    /**
     * Returns all available command names.
     * @return array all available command names
     */
    public function getCommands()
    {
        $commands = $this->getModuleCommands(Yii::$app);
        sort($commands);
        return array_unique($commands);
    }

    /**
     * Returns an array of commands an their descriptions.
     * @return array all available commands as keys and their description as values.
     */
    protected function getCommandDescriptions()
    {
        $descriptions = [];
        foreach ($this->getCommands() as $command) {
            $description = '';

            $result = Yii::$app->createController($command);
            if ($result !== false) {
                list($controller, $actionID) = $result;
98 99
                /** @var Controller $controller */
                $description = $controller->getHelpSummary();
100 101 102 103 104 105 106 107 108 109
            }

            $descriptions[$command] = $description;
        }

        return $descriptions;
    }

    /**
     * Returns all available actions of the specified controller.
110 111
     * @param Controller $controller the controller instance
     * @return array all available action IDs.
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
     */
    public function getActions($controller)
    {
        $actions = array_keys($controller->actions());
        $class = new \ReflectionClass($controller);
        foreach ($class->getMethods() as $method) {
            $name = $method->getName();
            if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0 && $name !== 'actions') {
                $actions[] = Inflector::camel2id(substr($name, 6));
            }
        }
        sort($actions);

        return array_unique($actions);
    }

    /**
     * Returns available commands of a specified module.
130 131
     * @param \yii\base\Module $module the module instance
     * @return array the available command names
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
     */
    protected function getModuleCommands($module)
    {
        $prefix = $module instanceof Application ? '' : $module->getUniqueID() . '/';

        $commands = [];
        foreach (array_keys($module->controllerMap) as $id) {
            $commands[] = $prefix . $id;
        }

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

        $controllerPath = $module->getControllerPath();
        if (is_dir($controllerPath)) {
            $files = scandir($controllerPath);
            foreach ($files as $file) {
155
                if (!empty($file) && substr_compare($file, 'Controller.php', -14) === 0) {
156 157 158 159
                    $controllerClass = $module->controllerNamespace . '\\' . substr(basename($file), 0, -4);
                    if ($this->validateControllerClass($controllerClass)) {
                        $commands[] = $prefix . Inflector::camel2id(substr(basename($file), 0, -14));
                    }
160 161 162 163 164 165 166
                }
            }
        }

        return $commands;
    }

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    /**
     * Validates if the given class is a valid console controller class.
     * @param string $controllerClass
     * @return bool
     */
    protected function validateControllerClass($controllerClass)
    {
        if (class_exists($controllerClass)) {
            $class = new \ReflectionClass($controllerClass);
            return !$class->isAbstract() && $class->isSubclassOf('yii\console\Controller');
        } else {
            return false;
        }
    }

182 183 184
    /**
     * Displays all available commands.
     */
Carsten Brandt committed
185
    protected function getGlobalHelp()
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    {
        $commands = $this->getCommandDescriptions();
        if (!empty($commands)) {
            $this->stdout("\nThe following commands are available:\n\n", Console::BOLD);
            $len = 0;
            foreach ($commands as $command => $description) {
                if (($l = strlen($command)) > $len) {
                    $len = $l;
                }
            }
            foreach ($commands as $command => $description) {
                echo "- " . $this->ansiFormat($command, Console::FG_YELLOW);
                echo str_repeat(' ', $len + 3 - strlen($command)) . $description;
                echo "\n";
            }
            $scriptName = $this->getScriptName();
            $this->stdout("\nTo see the help of each command, enter:\n", Console::BOLD);
            echo "\n  $scriptName " . $this->ansiFormat('help', Console::FG_YELLOW) . ' '
                            . $this->ansiFormat('<command-name>', Console::FG_CYAN) . "\n\n";
        } else {
            $this->stdout("\nNo commands are found.\n\n", Console::BOLD);
        }
    }

    /**
     * Displays the overall information of the command.
     * @param Controller $controller the controller instance
     */
    protected function getControllerHelp($controller)
    {
Carsten Brandt committed
216
        // TODO set color option of controller to this controllers color option
217

Carsten Brandt committed
218 219
        $this->stdout("\nDESCRIPTION\n", Console::BOLD);
        $comment = $controller->getHelp();
220
        if ($comment !== '') {
Carsten Brandt committed
221
            $this->stdout("\n$comment\n\n");
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        }

        $actions = $this->getActions($controller);
        if (!empty($actions)) {
            $this->stdout("\nSUB-COMMANDS\n\n", Console::BOLD);
            $prefix = $controller->getUniqueId();
            foreach ($actions as $action) {
                echo '- ' . $this->ansiFormat($prefix.'/'.$action, Console::FG_YELLOW);
                if ($action === $controller->defaultAction) {
                    $this->stdout(' (default)', Console::FG_GREEN);
                }
                $summary = $this->getActionSummary($controller, $action);
                if ($summary !== '') {
                    echo ': ' . $summary;
                }
                echo "\n";
            }
            $scriptName = $this->getScriptName();
            echo "\nTo see the detailed information about individual sub-commands, enter:\n";
            echo "\n  $scriptName " . $this->ansiFormat('help', Console::FG_YELLOW) . ' '
                            . $this->ansiFormat('<sub-command>', Console::FG_CYAN) . "\n\n";
        }
    }

    /**
     * Returns the short summary of the action.
248 249 250
     * @param Controller $controller the controller instance
     * @param string $actionID action ID
     * @return string the summary about the action
251 252 253
     */
    protected function getActionSummary($controller, $actionID)
    {
254
        $description = null;
255
        $action = $controller->createAction($actionID);
256 257

        if ($action instanceof Action) {
258
            $description = $action->getHelpSummary();
259 260
        }
        if ($description === null) {
261
            $description = $controller->getActionHelpSummary($actionID);
262
        }
263
        return $description;
264 265 266 267
    }

    /**
     * Displays the detailed information of a command action.
268 269 270
     * @param Controller $controller the controller instance
     * @param string $actionID action ID
     * @throws Exception if the action does not exist
271
     */
272
    protected function getControllerActionHelp($controller, $actionID)
273 274 275 276 277 278 279
    {
        $action = $controller->createAction($actionID);
        if ($action === null) {
            throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', [
                'command' => rtrim($controller->getUniqueId() . '/' . $actionID, '/'),
            ]));
        }
280
        $description = null;
281
        if ($action instanceof InlineAction) {
282 283
            $method = new \ReflectionMethod($controller, $action->actionMethod);
        } else {
284
            /** @var Action $action */
285
            $description = $action->getHelp();
286 287 288 289 290 291
            $method = new \ReflectionMethod($action, 'run');
        }

        $tags = $this->parseComment($method->getDocComment());
        $options = $this->getOptionHelps($controller, $actionID);

292
        if ($description === null) {
293
            $description = $controller->getActionHelp($actionID);
294
        }
Carsten Brandt committed
295
        if ($description !== '') {
296
            $this->stdout("\nDESCRIPTION\n", Console::BOLD);
Carsten Brandt committed
297
            $this->stdout("\n$description\n\n");
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        }

        $this->stdout("\nUSAGE\n\n", Console::BOLD);
        $scriptName = $this->getScriptName();
        if ($action->id === $controller->defaultAction) {
            echo $scriptName . ' ' . $this->ansiFormat($controller->getUniqueId(), Console::FG_YELLOW);
        } else {
            echo $scriptName . ' ' . $this->ansiFormat($action->getUniqueId(), Console::FG_YELLOW);
        }
        list ($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : []);
        foreach ($required as $arg => $description) {
            $this->stdout(' <' . $arg . '>', Console::FG_CYAN);
        }
        foreach ($optional as $arg => $description) {
            $this->stdout(' [' . $arg . ']', Console::FG_CYAN);
        }
        if (!empty($options)) {
            $this->stdout(' [...options...]', Console::FG_RED);
        }
        echo "\n\n";

        if (!empty($required) || !empty($optional)) {
            echo implode("\n\n", array_merge($required, $optional)) . "\n\n";
        }

        if (!empty($options)) {
            $this->stdout("\nOPTIONS\n\n", Console::BOLD);
            echo implode("\n\n", $options) . "\n\n";
        }
    }

    /**
     * Returns the help information about arguments.
331 332 333
     * @param \ReflectionMethod $method
     * @param string $tags the parsed comment block related with arguments
     * @return array the required and optional argument help information
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
     */
    protected function getArgHelps($method, $tags)
    {
        if (is_string($tags)) {
            $tags = [$tags];
        }
        $params = $method->getParameters();
        $optional = $required = [];
        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()) {
                $optional[$name] = $this->formatOptionHelp('- ' . $this->ansiFormat($name, Console::FG_CYAN), false, $type, $param->getDefaultValue(), $comment);
            } else {
                $required[$name] = $this->formatOptionHelp('- ' . $this->ansiFormat($name, Console::FG_CYAN), true, $type, null, $comment);
            }
        }

        return [$required, $optional];
    }

    /**
     * Returns the help information about the options available for a console controller.
364 365 366
     * @param Controller $controller the console controller
     * @param string $actionID name of the action, if set include local options for that action
     * @return array the help information about the options
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
     */
    protected function getOptionHelps($controller, $actionID)
    {
        $optionNames = $controller->options($actionID);
        if (empty($optionNames)) {
            return [];
        }

        $class = new \ReflectionClass($controller);
        $options = [];
        foreach ($class->getProperties() as $property) {
            $name = $property->getName();
            if (!in_array($name, $optionNames, true)) {
                continue;
            }
            $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);
                }
                if (preg_match('/^([^\s]+)(.*)/s', $doc, $matches)) {
                    $type = $matches[1];
                    $comment = $matches[2];
                } else {
                    $type = null;
                    $comment = $doc;
                }
                $options[$name] = $this->formatOptionHelp($this->ansiFormat('--' . $name, Console::FG_RED), false, $type, $defaultValue, $comment);
            } else {
                $options[$name] = $this->formatOptionHelp($this->ansiFormat('--' . $name, Console::FG_RED), false, null, $defaultValue, '');
            }
        }
        ksort($options);

        return $options;
    }

    /**
     * Parses the comment block into tags.
408 409
     * @param string $comment the comment block
     * @return array the parsed tags
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
     */
    protected function parseComment($comment)
    {
        $tags = [];
        $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] = [$tags[$name], trim($matches[2])];
                }
            }
        }

        return $tags;
    }

    /**
     * Generates a well-formed string for an argument or option.
434 435 436 437 438 439
     * @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
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
     */
    protected function formatOptionHelp($name, $required, $type, $defaultValue, $comment)
    {
        $doc = '';
        $comment = trim($comment);

        if ($defaultValue !== null && !is_array($defaultValue)) {
            if ($type === null) {
                $type = gettype($defaultValue);
            }
            if (is_bool($defaultValue)) {
                // show as integer to avoid confusion
                $defaultValue = (int) $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";
    }

    /**
     * @return string the name of the cli script currently running.
     */
    protected function getScriptName()
    {
        return basename(Yii::$app->request->scriptFile);
    }
Zander Baldwin committed
477
}