Controller.php 17.5 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 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Action;
Qiang Xue committed
12
use yii\base\InlineAction;
Qiang Xue committed
13
use yii\base\InvalidRouteException;
14
use yii\helpers\Console;
Qiang Xue committed
15

Alexander Makarov committed
16
/**
Qiang Xue committed
17
 * Controller is the base class of console command classes.
Alexander Makarov committed
18
 *
Carsten Brandt committed
19
 * A console controller consists of one or several actions known as sub-commands.
Qiang Xue committed
20
 * Users call a console command by specifying the corresponding route which identifies a controller action.
21
 * The `yii` program is used when calling a console command, like the following:
Alexander Makarov committed
22
 *
Qiang Xue committed
23
 * ~~~
24
 * yii <route> [--param1=value1 --param2 ...]
Qiang Xue committed
25
 * ~~~
Alexander Makarov committed
26
 *
Carsten Brandt committed
27 28 29
 * where `<route>` is a route to a controller action and the params will be populated as properties of a command.
 * See [[options()]] for details.
 *
Alexander Makarov committed
30 31 32
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
33
class Controller extends \yii\base\Controller
Alexander Makarov committed
34
{
35 36 37
    const EXIT_CODE_NORMAL = 0;
    const EXIT_CODE_ERROR = 1;

38 39 40 41 42 43 44 45 46
    /**
     * @var boolean whether to run the command interactively.
     */
    public $interactive = true;
    /**
     * @var boolean whether to enable ANSI color in the output.
     * If not set, ANSI color will only be enabled for terminals that support it.
     */
    public $color;
47

48

49 50 51 52 53 54
    /**
     * Returns a value indicating whether ANSI color is enabled.
     *
     * ANSI color is enabled only if [[color]] is set true or is not set
     * and the terminal supports ANSI color.
     *
55 56
     * @param resource $stream the stream to check.
     * @return boolean Whether to enable ANSI style in output.
57
     */
58
    public function isColorEnabled($stream = \STDOUT)
59
    {
60
        return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
61
    }
62

63 64 65
    /**
     * Runs an action with the specified action ID and parameters.
     * If the action ID is empty, the method will use [[defaultAction]].
66 67 68
     * @param string $id the ID of the action to be executed.
     * @param array $params the parameters (name-value pairs) to be passed to the action.
     * @return integer the status of the action execution. 0 means normal, other values mean abnormal.
69
     * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
70
     * @throws Exception if there are unknown options or missing arguments
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
     * @see createAction
     */
    public function runAction($id, $params = [])
    {
        if (!empty($params)) {
            // populate options here so that they are available in beforeAction().
            $options = $this->options($id);
            foreach ($params as $name => $value) {
                if (in_array($name, $options, true)) {
                    $default = $this->$name;
                    $this->$name = is_array($default) ? preg_split('/\s*,\s*/', $value) : $value;
                    unset($params[$name]);
                } elseif (!is_int($name)) {
                    throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]));
                }
            }
        }
        return parent::runAction($id, $params);
    }
Qiang Xue committed
90

91 92 93 94 95
    /**
     * Binds the parameters to the action.
     * This method is invoked by [[Action]] when it begins to run with the given parameters.
     * This method will first bind the parameters with the [[options()|options]]
     * available to the action. It then validates the given arguments.
96 97 98
     * @param Action $action the action to be bound with parameters
     * @param array $params the parameters to be bound to the action
     * @return array the valid parameters that the action can run with.
99 100 101 102 103 104 105 106 107
     * @throws Exception if there are unknown options or missing arguments
     */
    public function bindActionParams($action, $params)
    {
        if ($action instanceof InlineAction) {
            $method = new \ReflectionMethod($this, $action->actionMethod);
        } else {
            $method = new \ReflectionMethod($action, 'run');
        }
108

109
        $args = array_values($params);
Qiang Xue committed
110

111 112 113 114 115 116 117 118 119 120 121 122 123
        $missing = [];
        foreach ($method->getParameters() as $i => $param) {
            if ($param->isArray() && isset($args[$i])) {
                $args[$i] = preg_split('/\s*,\s*/', $args[$i]);
            }
            if (!isset($args[$i])) {
                if ($param->isDefaultValueAvailable()) {
                    $args[$i] = $param->getDefaultValue();
                } else {
                    $missing[] = $param->getName();
                }
            }
        }
Qiang Xue committed
124

125 126 127
        if (!empty($missing)) {
            throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
        }
Alexander Makarov committed
128

129 130
        return $args;
    }
131

132 133 134 135 136 137 138 139 140 141 142
    /**
     * Formats a string with ANSI codes
     *
     * You may pass additional parameters using the constants defined in [[\yii\helpers\Console]].
     *
     * Example:
     *
     * ~~~
     * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
     * ~~~
     *
143
     * @param string $string the string to be formatted
144 145 146 147 148 149 150 151 152 153 154
     * @return string
     */
    public function ansiFormat($string)
    {
        if ($this->isColorEnabled()) {
            $args = func_get_args();
            array_shift($args);
            $string = Console::ansiFormat($string, $args);
        }
        return $string;
    }
155

156 157 158 159 160 161 162 163 164 165 166 167
    /**
     * Prints a string to STDOUT
     *
     * You may optionally format the string with ANSI codes by
     * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
     *
     * Example:
     *
     * ~~~
     * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
     * ~~~
     *
168
     * @param string $string the string to print
169 170 171 172 173 174 175 176 177 178 179
     * @return int|boolean Number of bytes printed or false on error
     */
    public function stdout($string)
    {
        if ($this->isColorEnabled()) {
            $args = func_get_args();
            array_shift($args);
            $string = Console::ansiFormat($string, $args);
        }
        return Console::stdout($string);
    }
Qiang Xue committed
180

181 182 183 184 185 186 187 188 189 190 191 192
    /**
     * Prints a string to STDERR
     *
     * You may optionally format the string with ANSI codes by
     * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
     *
     * Example:
     *
     * ~~~
     * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
     * ~~~
     *
193
     * @param string $string the string to print
194 195 196 197
     * @return int|boolean Number of bytes printed or false on error
     */
    public function stderr($string)
    {
198
        if ($this->isColorEnabled(\STDERR)) {
199 200 201 202
            $args = func_get_args();
            array_shift($args);
            $string = Console::ansiFormat($string, $args);
        }
203
        return fwrite(\STDERR, $string);
204
    }
205

206 207 208
    /**
     * Prompts the user for input and validates it
     *
209 210
     * @param string $text prompt string
     * @param array $options the options to validate the input:
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
     *
     *  - required: whether it is required or not
     *  - default: default value if no input is inserted by the user
     *  - pattern: regular expression pattern to validate user input
     *  - validator: a callable function to validate input. The function must accept two parameters:
     *      - $input: the user input to validate
     *      - $error: the error value passed by reference if validation failed.
     * @return string the user input
     */
    public function prompt($text, $options = [])
    {
        if ($this->interactive) {
            return Console::prompt($text, $options);
        } else {
            return isset($options['default']) ? $options['default'] : '';
        }
    }

    /**
     * Asks user to confirm by typing y or n.
     *
232 233
     * @param string $message to echo out before waiting for user input
     * @param boolean $default this value is returned if no selection is made.
234
     * @return boolean whether user confirmed.
235
     * Will return true if [[interactive]] is false.
236 237 238 239 240 241 242 243 244 245 246 247 248 249
     */
    public function confirm($message, $default = false)
    {
        if ($this->interactive) {
            return Console::confirm($message, $default);
        } else {
            return true;
        }
    }

    /**
     * Gives the user an option to choose from. Giving '?' as an input will show
     * a list of options to choose from and their explanations.
     *
250 251
     * @param string $prompt the prompt message
     * @param array $options Key-value array of options to choose from
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
     *
     * @return string An option character the user chose
     */
    public function select($prompt, $options = [])
    {
        return Console::select($prompt, $options);
    }

    /**
     * Returns the names of valid options for the action (id)
     * An option requires the existence of a public member variable whose
     * name is the option name.
     * Child classes may override this method to specify possible options.
     *
     * Note that the values setting via options are not available
     * until [[beforeAction()]] is being called.
     *
Alexander Makarov committed
269
     * @param string $actionID the action id of the current request
270
     * @return array the names of the options valid for the action
271
     */
Alexander Makarov committed
272
    public function options($actionID)
273
    {
Carsten Brandt committed
274
        // $actionId might be used in subclasses to provide options specific to action id
275 276
        return ['color', 'interactive'];
    }
Carsten Brandt committed
277 278

    /**
279
     * Returns one-line short summary describing this controller.
Carsten Brandt committed
280
     *
281 282
     * You may override this method to return customized summary.
     * The default implementation returns first line from the PHPDoc comment.
Carsten Brandt committed
283 284 285
     *
     * @return string
     */
286
    public function getHelpSummary()
Carsten Brandt committed
287
    {
288
        return $this->parseDocCommentSummary(new \ReflectionClass($this));
289 290
    }

Carsten Brandt committed
291
    /**
292
     * Returns help information for this controller.
Carsten Brandt committed
293
     *
294
     * You may override this method to return customized help.
295
     * The default implementation returns help information retrieved from the PHPDoc comment.
Carsten Brandt committed
296 297
     * @return string
     */
298
    public function getHelp()
Carsten Brandt committed
299
    {
300
        return $this->parseDocCommentDetail(new \ReflectionClass($this));
301
    }
302

303
    /**
304
     * Returns a one-line short summary describing the specified action.
305
     * @param Action $action action to get summary for
306
     * @return string a one-line short summary describing the specified action.
307
     */
308
    public function getActionHelpSummary($action)
309
    {
310
        return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
311
    }
312

313 314
    /**
     * Returns the detailed help information for the specified action.
315
     * @param Action $action action to get help for
316 317 318 319
     * @return string the detailed help information for the specified action.
     */
    public function getActionHelp($action)
    {
320 321 322 323 324 325 326 327 328 329 330 331 332 333 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 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
    }

    /**
     * Returns the help information for the anonymous arguments for the action.
     * The returned value should be an array. The keys are the argument names, and the values are
     * the corresponding help information. Each value must be an array of the following structure:
     *
     * - required: boolean, whether this argument is required.
     * - type: string, the PHP type of this argument.
     * - default: string, the default value of this argument
     * - comment: string, the comment of this argument
     *
     * The default implementation will return the help information extracted from the doc-comment of
     * the parameters corresponding to the action method.
     *
     * @param Action $action
     * @return array the help information of the action arguments
     */
    public function getActionArgsHelp($action)
    {
        $method = $this->getActionMethodReflection($action);
        $tags = $this->parseDocCommentTags($method);
        $params = isset($tags['param']) ? (array) $tags['param'] : [];

        $args = [];
        foreach ($method->getParameters() as $i => $reflection) {
            $name = $reflection->getName();
            $tag = isset($params[$i]) ? $params[$i] : '';
            if (preg_match('/^([^\s]+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
                $type = $matches[1];
                $comment = $matches[3];
            } else {
                $type = null;
                $comment = $tag;
            }
            if ($reflection->isDefaultValueAvailable()) {
                $args[$name] = [
                    'required' => false,
                    'type' => $type,
                    'default' => $reflection->getDefaultValue(),
                    'comment' => $comment,
                ];
            } else {
                $args[$name] = [
                    'required' => true,
                    'type' => $type,
                    'default' => null,
                    'comment' => $comment,
                ];
            }
        }
        return $args;
    }

    /**
     * Returns the help information for the options for the action.
     * The returned value should be an array. The keys are the option names, and the values are
     * the corresponding help information. Each value must be an array of the following structure:
     *
     * - type: string, the PHP type of this argument.
     * - default: string, the default value of this argument
     * - comment: string, the comment of this argument
     *
     * The default implementation will return the help information extracted from the doc-comment of
     * the properties corresponding to the action options.
     *
     * @param Action $action
     * @return array the help information of the action options
     */
    public function getActionOptionsHelp($action)
    {
        $optionNames = $this->options($action->id);
        if (empty($optionNames)) {
            return [];
        }

        $class = new \ReflectionClass($this);
        $options = [];
        foreach ($class->getProperties() as $property) {
            $name = $property->getName();
            if (!in_array($name, $optionNames, true)) {
                continue;
            }
            $defaultValue = $property->getValue($this);
            $tags = $this->parseDocCommentTags($property);
            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] = [
                    'type' => $type,
                    'default' => $defaultValue,
                    'comment' => $comment,
                ];
            } else {
                $options[$name] = [
                    'type' => null,
                    'default' => $defaultValue,
                    'comment' => '',
                ];
            }
        }
        return $options;
    }

    private $_reflections = [];

    /**
     * @param Action $action
     * @return \ReflectionMethod
     */
    protected function getActionMethodReflection($action)
    {
        if (!isset($this->_reflections[$action->id])) {
            if ($action instanceof InlineAction) {
                $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
            } else {
                $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
            }
        }
        return $this->_reflections[$action->id];
    }

    /**
     * Parses the comment block into tags.
     * @param \Reflector $reflection the comment block
     * @return array the parsed tags
     */
    protected function parseDocCommentTags($reflection)
    {
        $comment = $reflection->getDocComment();
        $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
        $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
        $tags = [];
        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;
    }

    /**
     * Returns the first line of docblock.
     *
     * @param \Reflector $reflection
     * @return string
     */
    protected function parseDocCommentSummary($reflection)
    {
        $docLines = preg_split('~\R~', $reflection->getDocComment());
        if (isset($docLines[1])) {
            return trim($docLines[1], ' *');
        }
        return '';
    }

    /**
     * Returns full description from the docblock.
     *
     * @param \Reflector $reflection
     * @return string
     */
    protected function parseDocCommentDetail($reflection)
    {
        $comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
        if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
            $comment = trim(substr($comment, 0, $matches[0][1]));
        }
        if ($comment !== '') {
            return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
507
        }
508
        return '';
Carsten Brandt committed
509
    }
Zander Baldwin committed
510
}