Commit b2662c0c by Qiang Xue

clean up help command.

parent 2d7f048b
...@@ -56,6 +56,15 @@ class Action extends Component ...@@ -56,6 +56,15 @@ class Action extends Component
} }
/** /**
* Returns the unique ID of this action among the whole application.
* @return string the unique ID of this action among the whole application.
*/
public function getUniqueId()
{
return $this->controller->getUniqueId() . '/' . $this->id;
}
/**
* Runs this action with the specified parameters. * Runs this action with the specified parameters.
* This method is mainly invoked by the controller. * This method is mainly invoked by the controller.
* @param array $params the parameters to be bound to the action's run() method. * @param array $params the parameters to be bound to the action's run() method.
......
...@@ -250,7 +250,7 @@ class Controller extends Component ...@@ -250,7 +250,7 @@ class Controller extends Component
*/ */
public function getRoute() public function getRoute()
{ {
return $this->action !== null ? $this->getUniqueId() . '/' . $this->action->id : $this->getUniqueId(); return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
} }
/** /**
......
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
namespace yii\console; namespace yii\console;
use yii\base\Exception;
use yii\base\InvalidRouteException; use yii\base\InvalidRouteException;
/** /**
...@@ -85,6 +84,7 @@ class Application extends \yii\base\Application ...@@ -85,6 +84,7 @@ class Application extends \yii\base\Application
* Processes the request. * Processes the request.
* The request is represented in terms of a controller route and action parameters. * The request is represented in terms of a controller route and action parameters.
* @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal) * @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
* @throws Exception if the script is not running from the command line
*/ */
public function processRequest() public function processRequest()
{ {
...@@ -93,7 +93,7 @@ class Application extends \yii\base\Application ...@@ -93,7 +93,7 @@ class Application extends \yii\base\Application
if ($request->getIsConsoleRequest()) { if ($request->getIsConsoleRequest()) {
return $this->runAction($request->route, $request->params); return $this->runAction($request->route, $request->params);
} else { } else {
throw new BadUsageException(\Yii::t('yii', 'this script must be run from the command line.')); throw new Exception(\Yii::t('yii', 'this script must be run from the command line.'));
} }
} }
...@@ -105,14 +105,14 @@ class Application extends \yii\base\Application ...@@ -105,14 +105,14 @@ class Application extends \yii\base\Application
* @param string $route the route that specifies the action. * @param string $route the route that specifies the action.
* @param array $params the parameters to be passed to 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. * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
* @throws BadUsageException if the route is invalid * @throws Exception if the route is invalid
*/ */
public function runAction($route, $params = array()) public function runAction($route, $params = array())
{ {
try { try {
return parent::runAction($route, $params); return parent::runAction($route, $params);
} catch (InvalidRouteException $e) { } catch (InvalidRouteException $e) {
throw new BadUsageException(\Yii::t('yii', 'Unknown command "{command}".', array('{command}' => $route))); throw new Exception(\Yii::t('yii', 'Unknown command "{command}".', array('{command}' => $route)));
} }
} }
......
...@@ -48,17 +48,14 @@ class Controller extends \yii\base\Controller ...@@ -48,17 +48,14 @@ class Controller extends \yii\base\Controller
public function runAction($id, $params = array()) public function runAction($id, $params = array())
{ {
if ($params !== array()) { if ($params !== array()) {
$class = new \ReflectionClass($this); $options = $this->globalOptions();
foreach ($params as $name => $value) { foreach ($params as $name => $value) {
if ($class->hasProperty($name)) { if (in_array($name, $options, true)) {
$property = $class->getProperty($name);
if ($property->isPublic() && !$property->isStatic() && $property->getDeclaringClass()->getName() === get_class($this)) {
$this->$name = $value; $this->$name = $value;
unset($params[$name]); unset($params[$name]);
} }
} }
} }
}
return parent::runAction($id, $params); return parent::runAction($id, $params);
} }
...@@ -69,16 +66,19 @@ class Controller extends \yii\base\Controller ...@@ -69,16 +66,19 @@ class Controller extends \yii\base\Controller
* @param Action $action the currently requested action * @param Action $action the currently requested action
* @param array $missingParams the names of the missing parameters * @param array $missingParams the names of the missing parameters
* @param array $unknownParams the unknown parameters (name=>value) * @param array $unknownParams the unknown parameters (name=>value)
* @throws BadUsageException if there are missing or unknown parameters * @throws Exception if there are missing or unknown parameters
*/ */
public function validateActionParams($action, $missingParams, $unknownParams) public function validateActionParams($action, $missingParams, $unknownParams)
{ {
unset($missingParams[Request::ANONYMOUS_PARAMS], $unknownParams[Request::ANONYMOUS_PARAMS]);
if (!empty($missingParams)) { if (!empty($missingParams)) {
throw new BadUsageException(Yii::t('yii', 'Missing required options: {params}', array( throw new Exception(Yii::t('yii', 'Missing required options: {params}', array(
'{params}' => implode(', ', $missingParams), '{params}' => implode(', ', $missingParams),
))); )));
} elseif (!empty($unknownParams)) { }
throw new BadUsageException(Yii::t('yii', 'Unknown options: {params}', array( if (!empty($unknownParams)) {
throw new Exception(Yii::t('yii', 'Unknown options: {params}', array(
'{params}' => implode(', ', $unknownParams), '{params}' => implode(', ', $unknownParams),
))); )));
} }
...@@ -102,6 +102,13 @@ class Controller extends \yii\base\Controller ...@@ -102,6 +102,13 @@ class Controller extends \yii\base\Controller
} }
} }
/**
* Returns the names of the global options for this command.
* A global option requires the existence of a global member variable whose
* name is the option name.
* Child classes may override this method to specify possible global options.
* @return array the names of the global options for this command.
*/
public function globalOptions() public function globalOptions()
{ {
return array(); return array();
......
<?php <?php
/** /**
* BadUsageException class file. * Exception class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright &copy; 2008 Yii Software LLC
...@@ -10,12 +10,12 @@ ...@@ -10,12 +10,12 @@
namespace yii\console; namespace yii\console;
/** /**
* BadUsageException represents an exception caused by incorrect usage of the end user. * Exception represents an exception caused by incorrect usage of a console command.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class BadUsageException extends \yii\base\Exception class Exception extends \yii\base\Exception
{ {
/** /**
* @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL) * @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL)
...@@ -27,7 +27,7 @@ class BadUsageException extends \yii\base\Exception ...@@ -27,7 +27,7 @@ class BadUsageException extends \yii\base\Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Bad Usage'); return \Yii::t('yii', 'Error');
} }
} }
...@@ -15,6 +15,8 @@ namespace yii\console; ...@@ -15,6 +15,8 @@ namespace yii\console;
*/ */
class Request extends \yii\base\Request class Request extends \yii\base\Request
{ {
const ANONYMOUS_PARAMS = 'args';
/** /**
* @var string the controller route specified by this request. If this is an empty string, * @var string the controller route specified by this request. If this is an empty string,
* it means the [[Application::defaultRoute|default route]] will be used. * it means the [[Application::defaultRoute|default route]] will be used.
...@@ -50,13 +52,13 @@ class Request extends \yii\base\Request ...@@ -50,13 +52,13 @@ class Request extends \yii\base\Request
$this->route = ''; $this->route = '';
} }
$this->params = array(); $this->params = array(self::ANONYMOUS_PARAMS => array());
foreach ($rawParams as $param) { foreach ($rawParams as $param) {
if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) { if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
$name = $matches[1]; $name = $matches[1];
$this->params[$name] = isset($matches[3]) ? $matches[3] : true; $this->params[$name] = isset($matches[3]) ? $matches[3] : true;
} else { } else {
$this->params['args'][] = $param; $this->params[self::ANONYMOUS_PARAMS][] = $param;
} }
} }
} }
......
...@@ -11,9 +11,10 @@ namespace yii\console\controllers; ...@@ -11,9 +11,10 @@ namespace yii\console\controllers;
use Yii; use Yii;
use yii\base\Application; use yii\base\Application;
use yii\console\BadUsageException; use yii\console\Exception;
use yii\base\InlineAction; use yii\base\InlineAction;
use yii\console\Controller; use yii\console\Controller;
use yii\console\Request;
use yii\util\StringHelper; use yii\util\StringHelper;
/** /**
...@@ -46,19 +47,17 @@ class HelpController extends Controller ...@@ -46,19 +47,17 @@ class HelpController extends Controller
* yiic help message # display help info about "message" * yiic help message # display help info about "message"
* ~~~ * ~~~
* *
* @param array $args additional anonymous command line arguments. * @param array $args The name of the command to show help about.
* You may provide a command name to display its detailed information. * If not provided, all available commands will be displayed.
* @return integer the exit status * @return integer the exit status
* @throws BadUsageException if the command for help is unknown * @throws Exception if the command for help is unknown
*/ */
public function actionIndex($args = array()) public function actionIndex($args = array())
{ {
if (empty($args)) { if (isset($args[0])) {
$this->getHelp();
} else {
$result = Yii::$application->createController($args[0]); $result = Yii::$application->createController($args[0]);
if ($result === false) { if ($result === false) {
throw new BadUsageException(Yii::t('yii', 'No help for unknown command "{command}".', array( throw new Exception(Yii::t('yii', 'No help for unknown command "{command}".', array(
'{command}' => $args[0], '{command}' => $args[0],
))); )));
} }
...@@ -70,6 +69,8 @@ class HelpController extends Controller ...@@ -70,6 +69,8 @@ class HelpController extends Controller
} else { } else {
$this->getActionHelp($controller, $actionID); $this->getActionHelp($controller, $actionID);
} }
} else {
$this->getHelp();
} }
} }
...@@ -143,7 +144,7 @@ class HelpController extends Controller ...@@ -143,7 +144,7 @@ class HelpController extends Controller
{ {
$commands = $this->getCommands(); $commands = $this->getCommands();
if ($commands !== array()) { if ($commands !== array()) {
echo "\nUsage: yiic <command-name> [...options...]\n\n"; echo "Usage: yiic <command-name> [...options...] [...arguments...]\n\n";
echo "The following commands are available:\n\n"; echo "The following commands are available:\n\n";
foreach ($commands as $command) { foreach ($commands as $command) {
echo " * $command\n"; echo " * $command\n";
...@@ -168,35 +169,23 @@ class HelpController extends Controller ...@@ -168,35 +169,23 @@ class HelpController extends Controller
} }
if ($comment !== '') { if ($comment !== '') {
echo "\n" . $comment . "\n"; echo "\nDESCRIPTION\n";
} echo "\n" . $comment . "\n\n";
$options = $this->getGlobalOptions($class, $controller);
if ($options !== array()) {
echo "\nGLOBAL OPTIONS";
echo "\n--------------\n\n";
foreach ($options as $name => $description) {
echo " --$name";
if ($description != '') {
echo ": $description\n";
}
echo "\n";
}
} }
$actions = $this->getActions($controller); $actions = $this->getActions($controller);
if ($actions !== array()) { if ($actions !== array()) {
echo "\nSUB-COMMANDS"; echo "\nSUB-COMMANDS\n\n";
echo "\n------------\n\n";
$prefix = $controller->getUniqueId(); $prefix = $controller->getUniqueId();
foreach ($actions as $action) { foreach ($actions as $action) {
if ($controller->defaultAction === $action) { if ($controller->defaultAction === $action) {
echo " * $prefix (default)\n"; echo " * $prefix/$action (or $prefix)\n";
} else { } else {
echo " * $prefix/$action\n"; echo " * $prefix/$action\n";
} }
} }
echo "\n"; echo "\nTo see the help of each sub-command, enter:\n";
echo "\n yiic help <sub-command>\n\n";
} }
} }
...@@ -204,139 +193,178 @@ class HelpController extends Controller ...@@ -204,139 +193,178 @@ class HelpController extends Controller
* Displays the detailed information of a command action. * Displays the detailed information of a command action.
* @param Controller $controller the controller instance * @param Controller $controller the controller instance
* @param string $actionID action ID * @param string $actionID action ID
* @throws BadUsageException if the action does not exist * @throws Exception if the action does not exist
*/ */
protected function getActionHelp($controller, $actionID) protected function getActionHelp($controller, $actionID)
{ {
$action = $controller->createAction($actionID); $action = $controller->createAction($actionID);
if ($action === null) { if ($action === null) {
throw new BadUsageException(Yii::t('yii', 'No help for unknown sub-command "{command}".', array( throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', array(
'{command}' => $controller->getUniqueId() . "/$actionID", '{command}' => $action->getUniqueId(),
))); )));
} }
if ($action instanceof InlineAction) { if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($controller, 'action' . $action->id); $method = new \ReflectionMethod($controller, $action->actionMethod);
} else { } else {
$method = new \ReflectionMethod($action, 'run'); $method = new \ReflectionMethod($action, 'run');
} }
$comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($method->getDocComment(), '/'))), "\r", '');
if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) { $tags = $this->parseComment($method->getDocComment());
$meta = substr($comment, $matches[0][1]); $options = $this->getOptions($method, isset($tags['param']) ? $tags['param'] : array());
$comment = trim(substr($comment, 0, $matches[0][1])); $globalOptions = $this->getGlobalOptions($controller);
$options = array_merge($options, $globalOptions);
echo "\nUSAGE\n\n";
if ($action->id === $controller->defaultAction) {
echo 'yiic ' . $controller->getUniqueId();
} else { } else {
$meta = ''; echo "yiic " . $action->getUniqueId();
} }
if (isset($options[Request::ANONYMOUS_PARAMS])) {
if (count($options) > 1) {
echo ' [...options...]';
}
echo " [...arguments...]";
} elseif (count($options)) {
echo " [...options...]";
}
echo "\n\n";
if ($comment !== '') { if ($tags['description'] !== '') {
echo "\n" . $comment . "\n"; echo "\nDESCRIPTION";
echo "\n\n" . $tags['description'] . "\n\n";
}
if (isset($options[Request::ANONYMOUS_PARAMS])) {
echo "\nARGUMENTS\n\n";
echo $options[Request::ANONYMOUS_PARAMS] . "\n\n";
unset($options[Request::ANONYMOUS_PARAMS]);
} }
$options = $this->getOptions($method, $meta);
if ($options !== array()) { if ($options !== array()) {
echo "\nOPTIONS"; echo "\nOPTIONS\n\n";
echo "\n-------\n\n"; echo implode("\n\n", $options) . "\n\n";
foreach ($options as $name => $description) { }
echo " --$name";
if ($description != '') {
echo ": $description\n";
} }
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]));
} }
echo "\n";
} }
} }
return $tags;
}
/** /**
* @param \ReflectionMethod $method * @param \ReflectionMethod $method
* @param string $meta * @param string $meta
* @return array * @return array
*/ */
protected function getOptions($method, $meta) protected function getOptions($method, $tags)
{ {
if (is_string($tags)) {
$tags = array($tags);
}
$params = $method->getParameters(); $params = $method->getParameters();
$tags = preg_split('/^\s*@/m', $meta, -1, PREG_SPLIT_NO_EMPTY); $optional = $required = array();
$options = array(); foreach ($params as $i => $param) {
$count = 0; $name = $param->getName();
foreach ($tags as $tag) { $tag = isset($tags[$i]) ? $tags[$i] : '';
$parts = preg_split('/\s+/', trim($tag), 2); if (preg_match('/^([^\s]+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
if ($parts[0] === 'param' && isset($params[$count])) {
$param = $params[$count];
$comment = isset($parts[1]) ? $parts[1] : '';
if (preg_match('/^([^\s]+)\s+(\$\w+\s+)?(.*)/s', $comment, $matches)) {
$type = $matches[1]; $type = $matches[1];
$doc = $matches[3]; $comment = $matches[3];
} else { } else {
$type = $comment; $type = null;
$doc = ''; $comment = $tag;
} }
$comment = $type === '' ? '' : ($type . ', ');
if ($param->isDefaultValueAvailable()) { if ($param->isDefaultValueAvailable()) {
$value = $param->getDefaultValue(); $optional[$name] = $this->formatOptionHelp($name, false, $type, $param->getDefaultValue(), $comment);
if (!is_array($value)) {
$comment .= 'optional (defaults to ' . var_export($value, true) . ').';
} else { } else {
$comment .= 'optional.'; $required[$name] = $this->formatOptionHelp($name, true, $type, null, $comment);
} }
} else {
$comment .= 'required.';
} }
if (trim($doc) !== '') {
$comment .= "\n" . preg_replace("/^/m", " ", $doc); ksort($required);
ksort($optional);
return array_merge($required, $optional);
} }
$options[$param->getName()] = $comment;
$count++; protected function formatOptionHelp($name, $required, $type, $defaultValue, $comment)
{
$doc = '';
$comment = trim($comment);
if ($name === Request::ANONYMOUS_PARAMS) {
return $comment;
} }
if ($defaultValue !== null && !is_array($defaultValue)) {
if ($type === null) {
$type = gettype($defaultValue);
} }
if ($count < count($params)) { $doc = "$type (defaults to " . var_export($defaultValue, true) . ")";
for ($i = $count; $i < count($params); ++$i) { } elseif (trim($type) !== '') {
$options[$params[$i]->getName()] = ''; $doc = $type;
} }
if ($doc === '') {
$doc = $comment;
} elseif ($comment !== '') {
$doc .= "\n" . preg_replace("/^/m", " ", $comment);
} }
ksort($options); $name = $required ? "--$name (required)" : "--$name";
return $options; return $doc === '' ? $name : "$name: $doc";
} }
/** /**
* @param \ReflectionClass $class
* @param Controller $controller * @param Controller $controller
* @return array * @return array
*/ */
protected function getGlobalOptions($class, $controller) protected function getGlobalOptions($controller)
{ {
$optionNames = $controller->globalOptions();
if (empty($optionNames)) {
return array();
}
$class = new \ReflectionClass($controller);
$options = array(); $options = array();
foreach ($class->getProperties() as $property) { foreach ($class->getProperties() as $property) {
if (!$property->isPublic() || $property->isStatic() || $property->getDeclaringClass()->getName() !== get_class($controller)) { $name = $property->getName();
if (!in_array($name, $optionNames, true)) {
continue; continue;
} }
$name = $property->getName(); $defaultValue = $property->getValue($controller);
$comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($property->getDocComment(), '/'))), "\r", ''); $tags = $this->parseComment($property->getDocComment());
if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) { if (isset($tags['var']) || isset($tags['property'])) {
$meta = substr($comment, $matches[0][1]); $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
} else { if (is_array($doc)) {
$meta = ''; $doc = reset($doc);
} }
$tags = preg_split('/^\s*@/m', $meta, -1, PREG_SPLIT_NO_EMPTY); if (preg_match('/^([^\s]+)(.*)/s', $doc, $matches)) {
foreach ($tags as $tag) {
$parts = preg_split('/\s+/', trim($tag), 2);
$comment = isset($parts[1]) ? $parts[1] : '';
if ($parts[0] === 'var' || $parts[0] === 'property') {
if (preg_match('/^([^\s]+)(\s+.*)?/s', $comment, $matches)) {
$type = $matches[1]; $type = $matches[1];
$doc = trim($matches[2]); $comment = $matches[2];
} else { } else {
$type = $comment; $type = null;
$doc = ''; $comment = $doc;
}
$comment = $type === '' ? '' : ($type);
if (trim($doc) !== '') {
$comment .= ', ' . preg_replace("/^/m", "", $doc);
} }
$options[$name] = $comment; $options[$name] = $this->formatOptionHelp($name, false, $type, $defaultValue, $comment);
break; } else {
} $options[$name] = $this->formatOptionHelp($name, false, null, $defaultValue, '');
}
if (!isset($options[$name])) {
$options[$name] = '';
} }
} }
ksort($options); ksort($options);
......
...@@ -11,15 +11,13 @@ ...@@ -11,15 +11,13 @@
namespace yii\console\controllers; namespace yii\console\controllers;
use Yii; use Yii;
use yii\console\Exception;
use yii\console\Controller; use yii\console\Controller;
use yii\db\Connection;
/** /**
* This command provides support for database migrations. * This command provides support for database migrations.
* *
* The implementation of this command and other supporting classes referenced
* the yii-dbmigrations extension ((https://github.com/pieterclaerhout/yii-dbmigrations),
* authored by Pieter Claerhout.
*
* EXAMPLES * EXAMPLES
* *
* - yiic migrate * - yiic migrate
...@@ -61,53 +59,70 @@ use yii\console\Controller; ...@@ -61,53 +59,70 @@ use yii\console\Controller;
*/ */
class MigrateController extends Controller class MigrateController extends Controller
{ {
/**
* The name of the dummy migration that marks the beginning of the whole migration history.
*/
const BASE_MIGRATION = 'm000000_000000_base'; const BASE_MIGRATION = 'm000000_000000_base';
/** /**
* @var string the directory that stores the migrations. This must be specified * @var string the directory that stores the migrations. This can be either a path alias
* in terms of a path alias, and the corresponding directory must exist. * or a directory. Defaults to '@application/migrations'.
* Defaults to 'application.migrations' (meaning 'protected/migrations').
*/ */
public $migrationPath = '@application/migrations'; public $migrationPath = '@application/migrations';
/** /**
* @var string the name of the table for keeping applied migration information. * @var string the name of the table for keeping applied migration information.
* This table will be automatically created if not exists. Defaults to 'tbl_migration'. * This table will be automatically created if not exists.
* The table structure is: (version varchar(255) primary key, apply_time integer) * The table structure is as follows:
*
* ~~~
* CREATE TABLE tbl_migration (
* version varchar(255) PRIMARY KEY,
* apply_time integer
* )
* ~~~
*/ */
public $migrationTable = 'tbl_migration'; public $migrationTable = 'tbl_migration';
/** /**
* @var string the application component ID that specifies the database connection for * @var string the component ID that specifies the database connection for
* storing migration information. Defaults to 'db'. * storing migration information.
*/ */
public $connectionID = 'db'; public $connectionID = 'db';
/** /**
* @var string the path of the template file for generating new migrations. This * @var string the path of the template file for generating new migrations.
* must be specified in terms of a path alias (e.g. application.migrations.template). * This can be either a path alias (e.g. "@application/migrations/template.php")
* If not set, an internal template will be used. * or a file path. If not set, an internal template will be used.
*/ */
public $templateFile; public $templateFile;
/** /**
* @var string the default command action. It defaults to 'up'. * @var string the default command action.
*/ */
public $defaultAction = 'up'; public $defaultAction = 'up';
/** /**
* @var boolean whether to execute the migration in an interactive mode. Defaults to true. * @var boolean whether to execute the migration in an interactive mode.
* Set this to false when performing migration in a cron job or background process.
*/ */
public $interactive = true; public $interactive = true;
public function globalOptions()
{
return array('migrationPath', 'migrationTable', 'connectionID', 'templateFile', 'interactive');
}
/**
* This method is invoked right before an action is to be executed (after all possible filters.)
* It checks the existence of the [[migrationPath]].
* @param \yii\base\Action $action the action to be executed.
* @return boolean whether the action should continue to be executed.
* @throws Exception if the migration directory does not exist.
*/
public function beforeAction($action) public function beforeAction($action)
{ {
if (parent::beforeAction($action)) { if (parent::beforeAction($action)) {
$path = Yii::getAlias($this->migrationPath); $path = Yii::getAlias($this->migrationPath);
if ($path === false || !is_dir($path)) { if ($path === false || !is_dir($path)) {
echo 'Error: the migration directory does not exist "' . $this->migrationPath . "\"\n"; throw new Exception("The migration directory \"{$this->migrationPath}\" does not exist.");
return false;
} }
$this->migrationPath = $path; $this->migrationPath = $path;
$version = Yii::getVersion(); $version = Yii::getVersion();
echo "\nYii Migration Tool v2.0 (based on Yii v{$version})\n\n"; echo "\nYii Migration Tool (based on Yii v{$version})\n\n";
return true; return true;
} else { } else {
return false; return false;
...@@ -115,7 +130,15 @@ class MigrateController extends Controller ...@@ -115,7 +130,15 @@ class MigrateController extends Controller
} }
/** /**
* @param array $args * Upgrades the application by applying new migrations. For example,
*
* ~~~
* yiic migrate # apply all new migrations
* yiic migrate 3 # apply the first 3 new migrations
* ~~~
*
* @param array $args the number of new migrations to be applied. If not provided,
* all new migrations will be applied.
*/ */
public function actionUp($args) public function actionUp($args)
{ {
...@@ -145,7 +168,7 @@ class MigrateController extends Controller ...@@ -145,7 +168,7 @@ class MigrateController extends Controller
if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) {
foreach ($migrations as $migration) { foreach ($migrations as $migration) {
if ($this->migrateUp($migration) === false) { if ($this->migrateUp($migration) === false) {
echo "\nMigration failed. All later migrations are canceled.\n"; echo "\nMigration failed. The rest of the new migrations are canceled.\n";
return; return;
} }
} }
...@@ -153,11 +176,23 @@ class MigrateController extends Controller ...@@ -153,11 +176,23 @@ class MigrateController extends Controller
} }
} }
/**
* Downgrades the application by reverting old migrations. For example,
*
* ~~~
* yiic migrate/down # revert the last migration
* yiic migrate/down 3 # revert the last 3 migrations
* ~~~
*
* @param array $args the number of migrations to be reverted. If not provided,
* the last applied migration will be reverted.
* @throws Exception if the number of the steps is less than 1.
*/
public function actionDown($args) public function actionDown($args)
{ {
$step = isset($args[0]) ? (int)$args[0] : 1; $step = isset($args[0]) ? (int)$args[0] : 1;
if ($step < 1) { if ($step < 1) {
die("Error: The step parameter must be greater than 0.\n"); throw new Exception("The step parameter must be greater than 0.");
} }
if (($migrations = $this->getMigrationHistory($step)) === array()) { if (($migrations = $this->getMigrationHistory($step)) === array()) {
...@@ -226,14 +261,14 @@ class MigrateController extends Controller ...@@ -226,14 +261,14 @@ class MigrateController extends Controller
if (isset($args[0])) { if (isset($args[0])) {
$version = $args[0]; $version = $args[0];
} else { } else {
$this->usageError('Please specify which version to migrate to.'); throw new Exception("Please specify which version to migrate to.");
} }
$originalVersion = $version; $originalVersion = $version;
if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) { if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) {
$version = 'm' . $matches[1]; $version = 'm' . $matches[1];
} else { } else {
die("Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).\n"); throw new Exception("The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).");
} }
// try migrate up // try migrate up
...@@ -258,7 +293,7 @@ class MigrateController extends Controller ...@@ -258,7 +293,7 @@ class MigrateController extends Controller
} }
} }
die("Error: Unable to find the version '$originalVersion'.\n"); throw new Exception("Unable to find the version '$originalVersion'.");
} }
public function actionMark($args) public function actionMark($args)
...@@ -266,13 +301,13 @@ class MigrateController extends Controller ...@@ -266,13 +301,13 @@ class MigrateController extends Controller
if (isset($args[0])) { if (isset($args[0])) {
$version = $args[0]; $version = $args[0];
} else { } else {
$this->usageError('Please specify which version to mark to.'); throw new Exception('Please specify which version to mark to.');
} }
$originalVersion = $version; $originalVersion = $version;
if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) { if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) {
$version = 'm' . $matches[1]; $version = 'm' . $matches[1];
} else { } else {
die("Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).\n"); throw new Exception("Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).");
} }
$db = $this->getDb(); $db = $this->getDb();
...@@ -357,12 +392,17 @@ class MigrateController extends Controller ...@@ -357,12 +392,17 @@ class MigrateController extends Controller
} }
} }
/**
* Creates a new migration.
* @param array $args the name of the new migration.
* @throws Exception if the name of the new migration is not provided
*/
public function actionCreate($args) public function actionCreate($args)
{ {
if (isset($args[0])) { if (isset($args[0])) {
$name = $args[0]; $name = $args[0];
} else { } else {
$this->usageError('Please provide the name of the new migration.'); throw new Exception('Please provide the name of the new migration.');
} }
if (!preg_match('/^\w+$/', $name)) { if (!preg_match('/^\w+$/', $name)) {
...@@ -428,7 +468,7 @@ class MigrateController extends Controller ...@@ -428,7 +468,7 @@ class MigrateController extends Controller
$file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
require_once($file); require_once($file);
$migration = new $class; $migration = new $class;
$migration->setDb($this->getDb()); $migration->db = $this->getDb();
return $migration; return $migration;
} }
...@@ -445,7 +485,7 @@ class MigrateController extends Controller ...@@ -445,7 +485,7 @@ class MigrateController extends Controller
if (($this->_db = Yii::$application->getComponent($this->connectionID)) instanceof CDbConnection) { if (($this->_db = Yii::$application->getComponent($this->connectionID)) instanceof CDbConnection) {
return $this->_db; return $this->_db;
} else { } else {
die("Error: CMigrationCommand.connectionID '{$this->connectionID}' is invalid. Please make sure it refers to the ID of a CDbConnection application component.\n"); throw new Exception("Invalid DB connection: {$this->connectionID}.");
} }
} }
} }
...@@ -505,7 +545,7 @@ class MigrateController extends Controller ...@@ -505,7 +545,7 @@ class MigrateController extends Controller
protected function getTemplate() protected function getTemplate()
{ {
if ($this->templateFile !== null) { if ($this->templateFile !== null) {
return file_get_contents(Yii::getPathOfAlias($this->templateFile) . '.php'); return file_get_contents(Yii::getAlias($this->templateFile));
} else { } else {
return <<<EOD return <<<EOD
<?php <?php
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment