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.

84 lines
2.3 KiB

13 years ago
<?php
/**
* Action class file.
13 years ago
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
13 years ago
/**
* Action is the base class for all controller action classes.
13 years ago
*
* Action provides a way to divide a complex controller into
13 years ago
* smaller actions in separate class files.
*
13 years ago
* Derived classes must implement a method named `run()`. This method
* will be invoked by the controller when the action is requested.
* The `run()` method can have parameters which will be filled up
* automatically according to their names.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
13 years ago
*/
class Action extends Component
13 years ago
{
/**
* @var string ID of the action
13 years ago
*/
public $id;
13 years ago
/**
* @var Controller the controller that owns this action
13 years ago
*/
public $controller;
13 years ago
/**
13 years ago
* Runs the action with the supplied parameters.
* This method is invoked by the controller.
* @param array $params the input parameters in terms of name-value pairs.
* @return boolean whether the input parameters are valid
13 years ago
*/
13 years ago
public function runWithParams($params)
13 years ago
{
$method = new \ReflectionMethod($this, 'run');
13 years ago
$params = $this->normalizeParamsByMethod($method, $params);
if ($params !== false) {
call_user_func_array(array($this, 'run'), $params);
return true;
} else {
return false;
}
13 years ago
}
/**
* Extracts the input parameters according to the specified method signature.
* @param \ReflectionMethod $method the method reflection
* @param array $params the parameters in name-value pairs
* @return array|boolean the extracted parameters in the order as declared in the "run()" method.
* False is returned if the input parameters do not follow the method declaration.
13 years ago
*/
protected function normalizeParamsByMethod($method, $params)
13 years ago
{
$ps = array();
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (isset($params[$name])) {
if ($param->isArray()) {
$ps[] = is_array($params[$name]) ? $params[$name] : array($params[$name]);
} elseif (!is_array($params[$name])) {
$ps[] = $params[$name];
} else {
13 years ago
return false;
}
} elseif ($param->isDefaultValueAvailable()) {
$ps[] = $param->getDefaultValue();
} else {
13 years ago
return false;
}
13 years ago
}
return false;
13 years ago
}
}