Yii2 framework backup
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

342 lines
12 KiB

13 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\console;
12 years ago
use Yii;
13 years ago
use yii\base\Action;
12 years ago
use yii\base\InvalidRouteException;
use yii\helpers\Console;
13 years ago
13 years ago
/**
13 years ago
* Controller is the base class of console command classes.
13 years ago
*
10 years ago
* A console controller consists of one or several actions known as sub-commands.
13 years ago
* Users call a console command by specifying the corresponding route which identifies a controller action.
* The `yii` program is used when calling a console command, like the following:
13 years ago
*
13 years ago
* ~~~
* yii <route> [--param1=value1 --param2 ...]
13 years ago
* ~~~
13 years ago
*
10 years ago
* where `<route>` is a route to a controller action and the params will be populated as properties of a command.
* See [[options()]] for details.
*
13 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
13 years ago
class Controller extends \yii\base\Controller
13 years ago
{
const EXIT_CODE_NORMAL = 0;
const EXIT_CODE_ERROR = 1;
/**
* @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;
/**
* 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.
*
* @param resource $stream the stream to check.
* @return boolean Whether to enable ANSI style in output.
*/
public function isColorEnabled($stream = \STDOUT)
{
return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
}
/**
* Runs an action with the specified action ID and parameters.
* If the action ID is empty, the method will use [[defaultAction]].
* @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.
* @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
* @throws Exception if there are unknown options or missing arguments
* @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);
}
12 years ago
/**
* 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.
* @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.
* @throws Exception if there are unknown options or missing arguments
*/
public function bindActionParams($action, $params)
{
if ($action instanceof \yii\base\InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$args = array_values($params);
12 years ago
$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();
}
}
}
12 years ago
if (!empty($missing)) {
throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
}
return $args;
}
/**
* 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);
* ~~~
*
* @param string $string the string to be formatted
* @return string
*/
public function ansiFormat($string)
{
if ($this->isColorEnabled()) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return $string;
}
/**
* 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);
* ~~~
*
* @param string $string the string to print
* @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);
}
/**
* 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);
* ~~~
*
* @param string $string the string to print
* @return int|boolean Number of bytes printed or false on error
*/
public function stderr($string)
{
if ($this->isColorEnabled(\STDERR)) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return fwrite(\STDERR, $string);
}
/**
* Prompts the user for input and validates it
*
* @param string $text prompt string
* @param array $options the options to validate the input:
*
* - 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.
*
* @param string $message to echo out before waiting for user input
* @param boolean $default this value is returned if no selection is made.
* @return boolean whether user confirmed.
* Will return true if [[interactive]] is false.
*/
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.
*
* @param string $prompt the prompt message
* @param array $options Key-value array of options to choose from
*
* @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.
*
* @param string $actionId the action id of the current request
* @return array the names of the options valid for the action
*/
public function options($actionId)
{
10 years ago
// $actionId might be used in subclasses to provide options specific to action id
return ['color', 'interactive'];
}
10 years ago
/**
* Returns a short description (one line) of information about this controller or it's action (if specified).
10 years ago
*
* You may override this method to return customized description.
10 years ago
* The default implementation returns help information retrieved from the PHPDoc comments
* of the controller class.
*
* @param string $actionID action to get description for. null means overall controller description.
10 years ago
* @return string
*/
public function getDescription($actionID = null)
10 years ago
{
$action = null;
if ($actionID === null) {
$class = new \ReflectionClass($this);
} else {
$action = $this->createAction($actionID);
if ($action instanceof \yii\base\InlineAction) {
$class = new \ReflectionMethod($this, $action->actionMethod);
} else {
$class = new \ReflectionClass($action);
}
}
$docLines = preg_split('~\R~', $class->getDocComment());
10 years ago
if (isset($docLines[1])) {
return trim($docLines[1], ' *');
}
return '';
}
/**
* Returns help information for this controller or it's action (if specified).
10 years ago
*
* You may override this method to return customized help.
10 years ago
* The default implementation returns help information retrieved from the PHPDoc comments
* of the controller class.
* @param string $actionID action to get help for. null means overall controller help.
10 years ago
* @return string
*/
public function getHelp($actionID = null)
10 years ago
{
$action = null;
if ($actionID === null) {
$class = new \ReflectionClass($this);
} else {
$action = $this->createAction($actionID);
if ($action instanceof \yii\base\InlineAction) {
$class = new \ReflectionMethod($this, $action->actionMethod);
} else {
$class = new \ReflectionClass($action);
}
}
10 years ago
$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 !== '') {
return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
}
return '';
}
}