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,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