From d0d7498263d7ed74888885c66bfbfabfb9571b19 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Wed, 23 Jan 2013 14:50:44 -0500 Subject: [PATCH 01/14] todo updates. --- todo.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 7e5f256..7517b07 100644 --- a/todo.md +++ b/todo.md @@ -1,6 +1,6 @@ - db * pgsql, sql server, oracle, db2 drivers - * write a guide on creating own schema definitions + * unit tests on different DB drivers * document-based (should allow storage-specific methods additionally to generic ones) * mongodb (put it under framework/db/mongodb) * key-value-based (should allow storage-specific methods additionally to generic ones) @@ -8,8 +8,10 @@ - logging * WebTarget (TBD after web is in place): should consider using javascript and make it into a toolbar * ProfileTarget (TBD after web is in place): should consider using javascript and make it into a toolbar + * unit tests - caching * a console command to clear cached data + * unit tests - validators * FileValidator: depends on CUploadedFile * CaptchaValidator: depends on CaptchaAction From a6961f3404fdbe68b3cf707e161fd6815901c07e Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sat, 26 Jan 2013 00:21:04 +0100 Subject: [PATCH 02/14] patched controller and action creation --- framework/base/Application.php | 13 +++++++------ framework/base/Controller.php | 5 +++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/framework/base/Application.php b/framework/base/Application.php index 2e92aab..6d782ec 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -211,15 +211,16 @@ class Application extends Module */ public function runController($route, $params = array()) { - $result = $this->createController($route); - if ($result === false) { + list($controller, $action) = explode('/', $route); + + $controllerObject = $this->createController($controller, $this); + if ($controllerObject === false) { throw new InvalidRequestException(\Yii::t('yii', 'Unable to resolve the request.')); } - /** @var $controller Controller */ - list($controller, $action) = $result; + $priorController = $this->controller; - $this->controller = $controller; - $status = $controller->run($action, $params); + $this->controller = $controllerObject; + $status = $controllerObject->run($action, $params); $this->controller = $priorController; return $status; } diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 0df287a..d62cc35 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -142,8 +142,9 @@ class Controller extends Component if ($actionID === '') { $actionID = $this->defaultAction; } - if (isset($this->actionMap[$actionID])) { - return \Yii::createObject($this->actionMap[$actionID], $actionID, $this); + $actions = $this->actions(); + if (isset($actions[$actionID])) { + return \Yii::createObject($actions[$actionID], $actionID, $this); } elseif (method_exists($this, 'action' . $actionID)) { return new InlineAction($actionID, $this); } else { From ceac41b25041280b24a7e11956bac08acc8edad6 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Fri, 25 Jan 2013 18:56:56 -0500 Subject: [PATCH 03/14] MVC WIP --- framework/base/Application.php | 40 ++++++++----------- framework/base/Module.php | 91 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 105 insertions(+), 26 deletions(-) diff --git a/framework/base/Application.php b/framework/base/Application.php index 2e92aab..d2f463f 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -9,6 +9,7 @@ namespace yii\base; +use Yii; use yii\base\InvalidCallException; use yii\util\StringHelper; @@ -128,7 +129,7 @@ class Application extends Module */ public function __construct($id, $basePath, $config = array()) { - \Yii::$application = $this; + Yii::$application = $this; $this->id = $id; $this->setBasePath($basePath); $this->registerDefaultAliases(); @@ -213,7 +214,7 @@ class Application extends Module { $result = $this->createController($route); if ($result === false) { - throw new InvalidRequestException(\Yii::t('yii', 'Unable to resolve the request.')); + throw new InvalidRequestException(Yii::t('yii', 'Unable to resolve the request.')); } /** @var $controller Controller */ list($controller, $action) = $result; @@ -243,7 +244,7 @@ class Application extends Module */ public function setRuntimePath($path) { - $p = \Yii::getAlias($path); + $p = Yii::getAlias($path); if ($p === false || !is_dir($p) || !is_writable($path)) { throw new InvalidCallException("Application runtime path \"$path\" is invalid. Please make sure it is a directory writable by the Web server process."); } else { @@ -402,9 +403,9 @@ class Application extends Module */ public function registerDefaultAliases() { - \Yii::$aliases['@application'] = $this->getBasePath(); - \Yii::$aliases['@entry'] = dirname($_SERVER['SCRIPT_FILENAME']); - \Yii::$aliases['@www'] = ''; + Yii::$aliases['@application'] = $this->getBasePath(); + Yii::$aliases['@entry'] = dirname($_SERVER['SCRIPT_FILENAME']); + Yii::$aliases['@www'] = ''; } /** @@ -480,17 +481,15 @@ class Application extends Module return $this->runAction($route, $params, $childModule); } - /** @var $controller Controller */ - if (isset($module->controllerMap[$id])) { - $controller = \Yii::createObject($module->controllerMap[$id], $id, $module); - } else { - $controller = $this->createController($id, $module); - if ($controller === null) { - throw new InvalidRequestException("Unable to resolve the request: $route"); + $controller = $this->createController($id, $module); + if ($controller !== null) { + if ($route === '') { + $route = $controller->defaultAction; + if ($route == '') { + throw new InvalidConfigException(get_class($controller) . '::defaultAction cannot be empty.'); + } } - } - if (isset($controller)) { $action = $this->createAction($route, $controller); if ($action !== null) { return $action->runWithParams($params); @@ -516,7 +515,7 @@ class Application extends Module public function createController($id, $module) { if (isset($module->controllerMap[$id])) { - return \Yii::createObject($module->controllerMap[$id], $id, $module); + return Yii::createObject($module->controllerMap[$id], $id, $module); } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { $className = StringHelper::id2camel($id) . 'Controller'; $classFile = $module->controllerPath . DIRECTORY_SEPARATOR . $className . '.php'; @@ -541,18 +540,11 @@ class Application extends Module * @param string $id the action ID * @param Controller $controller the controller that owns the action * @return Action the newly created action instance - * @throws InvalidConfigException if [[Controller::defaultAction]] is empty. */ public function createAction($id, $controller) { - if ($id === '') { - $id = $controller->defaultAction; - if ($id == '') { - throw new InvalidConfigException(get_class($controller) . '::defaultAction cannot be empty.'); - } - } if (isset($controller->actionMap[$id])) { - return \Yii::createObject($controller->actionMap[$id], $id, $controller); + return Yii::createObject($controller->actionMap[$id], $id, $controller); } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { $methodName = 'action' . StringHelper::id2camel($id); if (method_exists($controller, $methodName)) { diff --git a/framework/base/Module.php b/framework/base/Module.php index 6337a9b..0539cdc 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -9,6 +9,8 @@ namespace yii\base; +use Yii; +use yii\util\StringHelper; use yii\util\FileHelper; /** @@ -167,12 +169,15 @@ abstract class Module extends Component /** * Returns an ID that uniquely identifies this module among all modules within the current application. + * Note that if the module is an application, an empty string will be returned. * @return string the unique ID of the module. */ public function getUniqueId() { - if ($this->module && !$this->module instanceof Application) { - return $this->module->getUniqueId() . "/{$this->id}"; + if ($this instanceof Application) { + return ''; + } elseif ($this->module) { + return $this->module->getUniqueId() . '/' . $this->id; } else { return $this->id; } @@ -533,4 +538,86 @@ abstract class Module extends Component $this->getComponent($id); } } + + /** + * Performs a controller action specified by a route. + * This method parses the specified route and creates the corresponding controller and action + * instances under the context of the specified module. It then runs the created action + * with the given parameters. + * @param string $route the route that specifies the action. + * @param array $params the parameters to be passed to the action + * @return integer the action + * @throws InvalidConfigException if the module's defaultRoute is empty or the controller's defaultAction is empty + * @throws InvalidRequestException if the requested route cannot be resolved into an action successfully + */ + public function runAction($route, $params = array()) + { + $route = trim($route, '/'); + if ($route === '') { + $route = trim($this->defaultRoute, '/'); + if ($route == '') { + throw new InvalidConfigException(get_class($this) . '::defaultRoute cannot be empty.'); + } + } + if (($pos = strpos($route, '/')) !== false) { + $id = substr($route, 0, $pos); + $route = substr($route, $pos + 1); + } else { + $id = $route; + $route = ''; + } + + $module = $this->getModule($id); + if ($module !== null) { + return $module->runAction($route, $params); + } + + $controller = $this->createController($id); + if ($controller !== null) { + if ($route === '') { + $route = $controller->defaultAction; + if ($route == '') { + throw new InvalidConfigException(get_class($controller) . '::defaultAction cannot be empty.'); + } + } + + $action = $controller->createAction($route); + if ($action !== null) { + return $action->runWithParams($params); + } + } + + throw new InvalidRequestException('Unable to resolve the request: ' . ltrim($this->getUniqueId() . '/' . $route, '/')); + } + + /** + * Creates a controller instance based on the controller ID. + * + * The controller is created within the given module. The method first attempts to + * create the controller based on the [[controllerMap]] of the module. If not available, + * it will look for the controller class under the [[controllerPath]] and create an + * instance of it. + * + * @param string $id the controller ID + * @return Controller the newly created controller instance + */ + public function createController($id) + { + if (isset($this->controllerMap[$id])) { + return Yii::createObject($this->controllerMap[$id], $id, $this); + } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { + $className = StringHelper::id2camel($id) . 'Controller'; + $classFile = $this->controllerPath . DIRECTORY_SEPARATOR . $className . '.php'; + if (is_file($classFile)) { + $className = $this->controllerNamespace . '\\' . $className; + if (!class_exists($className, false)) { + require($classFile); + } + if (class_exists($className, false) && is_subclass_of($className, '\yii\base\Controller')) { + return new $className($id, $this); + } + } + } + return null; + } } From 3fa22483c1317aeb28139a370ad1037443dee26d Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Sun, 27 Jan 2013 17:11:06 -0500 Subject: [PATCH 04/14] refactored logging. MVC WIP --- framework/YiiBase.php | 8 +- framework/base/Application.php | 291 +++++++------------------------ framework/base/Controller.php | 223 ++++++++++++----------- framework/base/InvalidRouteException.php | 21 +++ framework/base/Module.php | 128 +++++++------- framework/base/View.php | 2 +- framework/base/Widget.php | 2 +- framework/logging/DbTarget.php | 9 +- framework/logging/EmailTarget.php | 9 +- framework/logging/FileTarget.php | 25 ++- framework/logging/Logger.php | 33 ++-- framework/logging/Router.php | 21 +-- framework/logging/Target.php | 65 ++----- framework/util/FileHelper.php | 5 +- 14 files changed, 338 insertions(+), 504 deletions(-) create mode 100644 framework/base/InvalidRouteException.php diff --git a/framework/YiiBase.php b/framework/YiiBase.php index 9d3698b..1230053 100644 --- a/framework/YiiBase.php +++ b/framework/YiiBase.php @@ -121,8 +121,8 @@ class YiiBase * * To import a class or a directory, one can use either path alias or class name (can be namespaced): * - * - `@app/components/GoogleMap`: importing the `GoogleMap` class with a path alias; - * - `@app/components/*`: importing the whole `components` directory with a path alias; + * - `@application/components/GoogleMap`: importing the `GoogleMap` class with a path alias; + * - `@application/components/*`: importing the whole `components` directory with a path alias; * - `GoogleMap`: importing the `GoogleMap` class with a class name. [[autoload()]] will be used * when this class is used for the first time. * @@ -322,12 +322,12 @@ class YiiBase * the class. For example, * * - `\app\components\GoogleMap`: fully-qualified namespaced class. - * - `@app/components/GoogleMap`: an alias + * - `@application/components/GoogleMap`: an alias * * Below are some usage examples: * * ~~~ - * $object = \Yii::createObject('@app/components/GoogleMap'); + * $object = \Yii::createObject('@application/components/GoogleMap'); * $object = \Yii::createObject(array( * 'class' => '\app\components\GoogleMap', * 'apiKey' => 'xyz', diff --git a/framework/base/Application.php b/framework/base/Application.php index c618faa..6203d11 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -10,8 +10,8 @@ namespace yii\base; use Yii; +use yii\util\FileHelper; use yii\base\InvalidCallException; -use yii\util\StringHelper; /** * Application is the base class for all application classes. @@ -37,7 +37,7 @@ use yii\util\StringHelper; * Yii framework messages. This application component is dynamically loaded when needed. * * - * Application will undergo the following lifecycles when processing a user request: + * Application will undergo the following life cycles when processing a user request: *
    *
  1. load application configuration;
  2. *
  3. set up class autoloader and error handling;
  4. @@ -50,28 +50,6 @@ use yii\util\StringHelper; * Starting from lifecycle 3, if a PHP error or an uncaught exception occurs, * the application will switch to its error handling logic and jump to step 6 afterwards. * - * @property string $basePath Returns the root path of the application. - * @property CCache $cache Returns the cache component. - * @property CPhpMessageSource $coreMessages Returns the core message translations. - * @property CDateFormatter $dateFormatter Returns the locale-dependent date formatter. - * @property \yii\db\Connection $db Returns the database connection component. - * @property CErrorHandler $errorHandler Returns the error handler component. - * @property string $extensionPath Returns the root directory that holds all third-party extensions. - * @property string $id Returns the unique identifier for the application. - * @property string $language Returns the language that the user is using and the application should be targeted to. - * @property CLocale $locale Returns the locale instance. - * @property string $localeDataPath Returns the directory that contains the locale data. - * @property CMessageSource $messages Returns the application message translations component. - * @property CNumberFormatter $numberFormatter The locale-dependent number formatter. - * @property CHttpRequest $request Returns the request component. - * @property string $runtimePath Returns the directory that stores runtime files. - * @property CSecurityManager $securityManager Returns the security manager component. - * @property CStatePersister $statePersister Returns the state persister component. - * @property string $timeZone Returns the time zone used by this application. - * @property UrlManager $urlManager Returns the URL manager component. - * @property string $baseUrl Returns the relative URL for the application - * @property string $homeUrl the homepage URL - * * @author Qiang Xue * @since 2.0 */ @@ -134,7 +112,7 @@ class Application extends Module $this->setBasePath($basePath); $this->registerDefaultAliases(); $this->registerCoreComponents(); - parent::__construct($id, $this, $config); + Component::__construct($config); } /** @@ -204,27 +182,6 @@ class Application extends Module } /** - * Runs a controller with the given route and parameters. - * @param string $route the route (e.g. `post/create`) - * @param array $params the parameters to be passed to the controller action - * @return integer the exit status (0 means normal, non-zero values mean abnormal) - * @throws InvalidRequestException if the route cannot be resolved into a controller - */ - public function runController($route, $params = array()) - { - $result = $this->createController($route); - if ($result === false) { - throw new InvalidRequestException(Yii::t('yii', 'Unable to resolve the request.')); - } - - $priorController = $this->controller; - $this->controller = $controllerObject; - $status = $controllerObject->run($action, $params); - $this->controller = $priorController; - return $status; - } - - /** * Returns the directory that stores runtime files. * @return string the directory that stores runtime files. Defaults to 'protected/runtime'. */ @@ -239,15 +196,15 @@ class Application extends Module /** * Sets the directory that stores runtime files. * @param string $path the directory that stores runtime files. - * @throws InvalidCallException if the directory does not exist or is not writable + * @throws InvalidConfigException if the directory does not exist or is not writable */ public function setRuntimePath($path) { - $p = Yii::getAlias($path); - if ($p === false || !is_dir($p) || !is_writable($path)) { - throw new InvalidCallException("Application runtime path \"$path\" is invalid. Please make sure it is a directory writable by the Web server process."); - } else { + $p = FileHelper::ensureDirectory($path); + if (is_writable($p)) { $this->_runtimePath = $p; + } else { + throw new InvalidConfigException("Runtime path must be writable by the Web server process: $path"); } } @@ -296,34 +253,61 @@ class Application extends Module date_default_timezone_set($value); } - /** - * Returns the locale instance. - * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used. - * @return CLocale the locale instance - */ - public function getLocale($localeID = null) - { - return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID); - } - - /** - * @return CNumberFormatter the locale-dependent number formatter. - * The current {@link getLocale application locale} will be used. - */ - public function getNumberFormatter() - { - return $this->getLocale()->getNumberFormatter(); - } - - /** - * Returns the locale-dependent date formatter. - * @return CDateFormatter the locale-dependent date formatter. - * The current {@link getLocale application locale} will be used. - */ - public function getDateFormatter() - { - return $this->getLocale()->getDateFormatter(); - } +// /** +// * Returns the security manager component. +// * @return SecurityManager the security manager application component. +// */ +// public function getSecurityManager() +// { +// return $this->getComponent('securityManager'); +// } +// +// /** +// * Returns the locale instance. +// * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used. +// * @return CLocale the locale instance +// */ +// public function getLocale($localeID = null) +// { +// return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID); +// } +// +// /** +// * @return CNumberFormatter the locale-dependent number formatter. +// * The current {@link getLocale application locale} will be used. +// */ +// public function getNumberFormatter() +// { +// return $this->getLocale()->getNumberFormatter(); +// } +// +// /** +// * Returns the locale-dependent date formatter. +// * @return CDateFormatter the locale-dependent date formatter. +// * The current {@link getLocale application locale} will be used. +// */ +// public function getDateFormatter() +// { +// return $this->getLocale()->getDateFormatter(); +// } +// +// /** +// * Returns the core message translations component. +// * @return \yii\i18n\MessageSource the core message translations +// */ +// public function getCoreMessages() +// { +// return $this->getComponent('coreMessages'); +// } +// +// /** +// * Returns the application message translations component. +// * @return \yii\i18n\MessageSource the application message translations +// */ +// public function getMessages() +// { +// return $this->getComponent('messages'); +// } /** * Returns the database connection component. @@ -353,15 +337,6 @@ class Application extends Module } /** - * Returns the security manager component. - * @return SecurityManager the security manager application component. - */ - public function getSecurityManager() - { - return $this->getComponent('securityManager'); - } - - /** * Returns the cache component. * @return \yii\caching\Cache the cache application component. Null if the component is not enabled. */ @@ -371,24 +346,6 @@ class Application extends Module } /** - * Returns the core message translations component. - * @return \yii\i18n\MessageSource the core message translations - */ - public function getCoreMessages() - { - return $this->getComponent('coreMessages'); - } - - /** - * Returns the application message translations component. - * @return \yii\i18n\MessageSource the application message translations - */ - public function getMessages() - { - return $this->getComponent('messages'); - } - - /** * Returns the request component. * @return Request the request component */ @@ -417,15 +374,6 @@ class Application extends Module 'errorHandler' => array( 'class' => 'yii\base\ErrorHandler', ), - 'request' => array( - 'class' => 'yii\base\Request', - ), - 'response' => array( - 'class' => 'yii\base\Response', - ), - 'format' => array( - 'class' => 'yii\base\Formatter', - ), 'coreMessages' => array( 'class' => 'yii\i18n\PhpMessageSource', 'language' => 'en_us', @@ -442,117 +390,4 @@ class Application extends Module ), )); } - - /** - * Performs a controller action specified by a route. - * This method parses the specified route and creates the corresponding controller and action - * instances under the context of the specified module. It then runs the created action - * with the given parameters. - * @param string $route the route that specifies the action. - * @param array $params the parameters to be passed to the action - * @param Module $module the module which serves as the context of the route - * @return integer the action - * @throws InvalidConfigException if the module's defaultRoute is empty or the controller's defaultAction is empty - * @throws InvalidRequestException if the requested route cannot be resolved into an action successfully - */ - public function runAction($route, $params = array(), $module = null) - { - if ($module === null) { - $module = $this; - } - $route = trim($route, '/'); - if ($route === '') { - $route = trim($module->defaultRoute, '/'); - if ($route == '') { - throw new InvalidConfigException(get_class($module) . '::defaultRoute cannot be empty.'); - } - } - if (($pos = strpos($route, '/')) !== false) { - $id = substr($route, 0, $pos); - $route = substr($route, $pos + 1); - } else { - $id = $route; - $route = ''; - } - - $childModule = $module->getModule($id); - if ($childModule !== null) { - return $this->runAction($route, $params, $childModule); - } - - $controller = $this->createController($id, $module); - if ($controller !== null) { - if ($route === '') { - $route = $controller->defaultAction; - if ($route == '') { - throw new InvalidConfigException(get_class($controller) . '::defaultAction cannot be empty.'); - } - } - - $action = $this->createAction($route, $controller); - if ($action !== null) { - return $action->runWithParams($params); - } - } - - throw new InvalidRequestException("Unable to resolve the request: $route"); - } - - - /** - * Creates a controller instance based on the controller ID. - * - * The controller is created within the given module. The method first attempts to - * create the controller based on the [[controllerMap]] of the module. If not available, - * it will look for the controller class under the [[controllerPath]] and create an - * instance of it. - * - * @param string $id the controller ID - * @param Module $module the module that owns the controller - * @return Controller the newly created controller instance - */ - public function createController($id, $module) - { - if (isset($module->controllerMap[$id])) { - return Yii::createObject($module->controllerMap[$id], $id, $module); - } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { - $className = StringHelper::id2camel($id) . 'Controller'; - $classFile = $module->controllerPath . DIRECTORY_SEPARATOR . $className . '.php'; - if (is_file($classFile)) { - $className = $module->controllerNamespace . '\\' . $className; - if (!class_exists($className, false)) { - require($classFile); - } - if (class_exists($className, false) && is_subclass_of($className, '\yii\base\Controller')) { - return new $className($id, $module); - } - } - } - return null; - } - - /** - * Creates an action based on the given action ID. - * The action is created within the given controller. The method first attempts to - * create the action based on [[Controller::actions()]]. If not available, - * it will look for the inline action method within the controller. - * @param string $id the action ID - * @param Controller $controller the controller that owns the action - * @return Action the newly created action instance - */ - public function createAction($id, $controller) - { - if (isset($controller->actionMap[$id])) { - return Yii::createObject($controller->actionMap[$id], $id, $controller); - } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { - $methodName = 'action' . StringHelper::id2camel($id); - if (method_exists($controller, $methodName)) { - $method = new \ReflectionMethod($controller, $methodName); - if ($method->getName() === $methodName) { - return new InlineAction($id, $controller); - } - } - } - return null; - } } diff --git a/framework/base/Controller.php b/framework/base/Controller.php index d62cc35..79ad574 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -9,6 +9,9 @@ namespace yii\base; +use Yii; +use yii\util\StringHelper; + /** * Controller is the base class for classes containing controller logic. * @@ -27,6 +30,10 @@ namespace yii\base; */ class Controller extends Component { + const EVENT_AUTHORIZE = 'authorize'; + const EVENT_BEFORE_ACTION = 'beforeAction'; + const EVENT_AFTER_ACTION = 'afterAction'; + /** * @var string the ID of this controller */ @@ -91,65 +98,138 @@ class Controller extends Component } /** - * Runs the controller with the specified action and parameters. - * @param Action|string $action the action to be executed. This can be either an action object - * or the ID of the action. + * 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. - * If null, the result of [[getActionParams()]] will be used as action parameters. - * @return integer the exit status of the action. 0 means normal, other values mean abnormal. - * @see missingAction + * @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. * @see createAction */ - public function run($action, $params = null) + public function runAction($id, $params = array()) { - if (is_string($action)) { - if (($a = $this->createAction($action)) !== null) { - $action = $a; - } else { - $this->missingAction($action); - return 1; - } + if ($id === '') { + $id = $this->defaultAction; } - $priorAction = $this->action; - $this->action = $action; + $action = $this->createAction($id); + if ($action !== null) { + $oldAction = $this->action; + $this->action = $action; - if ($this->authorize($action) && $this->beforeAction($action)) { - if ($params === null) { - $params = $this->getActionParams(); + if ($this->authorize($action) && $this->beforeAction($action)) { + $status = $action->runWithParams($params); + $this->afterAction($action); + } else { + $status = 1; } - $status = $action->runWithParams($params); - $this->afterAction($action); + + $this->action = $oldAction; + + return $status; } else { - $status = 1; + throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id); } + } - $this->action = $priorAction; + /** + * Runs a request specified in terms of a route. + * The route can be either an ID of an action within this controller or a complete route consisting + * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of + * the route will start from the application; otherwise, it will start from the parent module of this controller. + * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'. + * @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. + * @see runAction + * @see forward + */ + public function run($route, $params = array()) + { + $pos = strpos($route, '/'); + if ($pos === false) { + return $this->runAction($route, $params); + } elseif ($pos > 0) { + return $this->module->runAction($route, $params); + } else { + return \Yii::$application->runAction($route, $params); + } + } - return $status; + /** + * Forwards the current execution flow to handle a new request specified by a route. + * The only difference between this method and [[run()]] is that after calling this method, + * the application will exit. + * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'. + * @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. + * @see run + */ + public function forward($route, $params = array()) + { + $status = $this->run($route, $params); + exit($status); } /** - * Creates the action instance based on the action ID. - * The action can be either an inline action or an object. - * The latter is created by looking up the action map specified in [[actions]]. - * @param string $actionID ID of the action. If empty, it will take the value of [[defaultAction]]. - * @return Action the action instance, null if the action does not exist. - * @see actions + * Creates an action based on the given action ID. + * The method first checks if the action ID has been declared in [[actions()]]. If so, + * it will use the configuration declared there to create the action object. + * If not, it will look for a controller method whose name is in the format of `actionXyz` + * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that + * method will be created and returned. + * @param string $id the action ID + * @return Action the newly created action instance. Null if the ID doesn't resolve into any action. */ - public function createAction($actionID) + public function createAction($id) { - if ($actionID === '') { - $actionID = $this->defaultAction; - } - $actions = $this->actions(); - if (isset($actions[$actionID])) { - return \Yii::createObject($actions[$actionID], $actionID, $this); - } elseif (method_exists($this, 'action' . $actionID)) { - return new InlineAction($actionID, $this); - } else { - return null; + $actionMap = $this->actions(); + if (isset($actionMap[$id])) { + return Yii::createObject($actionMap[$id], $id, $this); + } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { + $methodName = 'action' . StringHelper::id2camel($id); + if (method_exists($this, $methodName)) { + $method = new \ReflectionMethod($this, $methodName); + if ($method->getName() === $methodName) { + return new InlineAction($id, $this); + } + } } + return null; + } + + /** + * This method is invoked when checking the access for the action to be executed. + * @param Action $action the action to be executed. + * @return boolean whether the action is allowed to be executed. + */ + public function authorize($action) + { + $event = new ActionEvent($action); + $this->trigger(self::EVENT_AUTHORIZE, $event); + return $event->isValid; + } + + /** + * This method is invoked right before an action is to be executed (after all possible filters.) + * You may override this method to do last-minute preparation for the action. + * @param Action $action the action to be executed. + * @return boolean whether the action should continue to be executed. + */ + public function beforeAction($action) + { + $event = new ActionEvent($action); + $this->trigger(self::EVENT_BEFORE_ACTION, $event); + return $event->isValid; + } + + /** + * This method is invoked right after an action is executed. + * You may override this method to do some postprocessing for the action. + * @param Action $action the action just executed. + */ + public function afterAction($action) + { + $this->trigger(self::EVENT_AFTER_ACTION, new ActionEvent($action)); } /** @@ -217,67 +297,6 @@ class Controller extends Component return $this->action !== null ? $this->getUniqueId() . '/' . $this->action->id : $this->getUniqueId(); } - /** - * Processes the request using another controller action. - * @param string $route the route of the new controller action. This can be an action ID, or a complete route - * with module ID (optional in the current module), controller ID and action ID. If the former, - * the action is assumed to be located within the current controller. - * @param array $params the parameters to be passed to the action. - * If null, the result of [[getActionParams()]] will be used as action parameters. - * Note that the parameters must be name-value pairs with the names corresponding to - * the parameter names as declared by the action. - * @param boolean $exit whether to end the application after this call. Defaults to true. - */ - public function forward($route, $params = array(), $exit = true) - { - if (strpos($route, '/') === false) { - $status = $this->run($route, $params); - } else { - if ($route[0] !== '/' && !$this->module instanceof Application) { - $route = '/' . $this->module->getUniqueId() . '/' . $route; - } - $status = \Yii::$application->runController($route, $params); - } - if ($exit) { - \Yii::$application->end($status); - } - } - - /** - * This method is invoked when checking the access for the action to be executed. - * @param Action $action the action to be executed. - * @return boolean whether the action is allowed to be executed. - */ - public function authorize($action) - { - $event = new ActionEvent($action); - $this->trigger(__METHOD__, $event); - return $event->isValid; - } - - /** - * This method is invoked right before an action is to be executed (after all possible filters.) - * You may override this method to do last-minute preparation for the action. - * @param Action $action the action to be executed. - * @return boolean whether the action should continue to be executed. - */ - public function beforeAction($action) - { - $event = new ActionEvent($action); - $this->trigger(__METHOD__, $event); - return $event->isValid; - } - - /** - * This method is invoked right after an action is executed. - * You may override this method to do some postprocessing for the action. - * @param Action $action the action just executed. - */ - public function afterAction($action) - { - $this->trigger(__METHOD__, new ActionEvent($action)); - } - public function render($view, $params = array()) { return $this->createView()->render($view, $params); diff --git a/framework/base/InvalidRouteException.php b/framework/base/InvalidRouteException.php new file mode 100644 index 0000000..8e82b40 --- /dev/null +++ b/framework/base/InvalidRouteException.php @@ -0,0 +1,21 @@ + + * @since 2.0 + */ +class InvalidRouteException extends \Exception +{ +} + diff --git a/framework/base/Module.php b/framework/base/Module.php index 0539cdc..23bd577 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -16,13 +16,19 @@ use yii\util\FileHelper; /** * Module is the base class for module and application classes. * - * Module mainly manages application components and sub-modules that belongs to a module. + * A module represents a sub-application which contains MVC elements by itself, such as + * models, views, controllers, etc. + * + * A module may consist of [[modules|sub-modules]]. + * + * [[components|Components]] may be registered with the module so that they are globally + * accessible within the module. * * @property string $uniqueId An ID that uniquely identifies this module among all modules within * the current application. * @property string $basePath The root directory of the module. Defaults to the directory containing the module class. * @property array $modules The configuration of the currently installed modules (module ID => configuration). - * @property array $components The application components (indexed by their IDs). + * @property array $components The components (indexed by their IDs) registered within this module. * @property array $import List of aliases to be imported. This property is write-only. * @property array $aliases List of aliases to be defined. This property is write-only. * @@ -36,7 +42,7 @@ abstract class Module extends Component */ public $params = array(); /** - * @var array the IDs of the application components that should be preloaded when this module is created. + * @var array the IDs of the components that should be preloaded when this module is created. */ public $preload = array(); /** @@ -88,27 +94,27 @@ abstract class Module extends Component /** * @var string the root directory of the module. */ - protected $_basePath; + private $_basePath; /** * @var string the root directory that contains view files for this module */ - protected $_viewPath; + private $_viewPath; /** * @var string the root directory that contains layout view files for this module. */ - protected $_layoutPath; + private $_layoutPath; /** * @var string the directory containing controller classes in the module. */ - protected $_controllerPath; + private $_controllerPath; /** * @var array child modules of this module */ - protected $_modules = array(); + private $_modules = array(); /** - * @var array application components of this module + * @var array components registered under this module */ - protected $_components = array(); + private $_components = array(); /** * Constructor. @@ -125,9 +131,9 @@ abstract class Module extends Component /** * Getter magic method. - * This method is overridden to support accessing application components + * This method is overridden to support accessing components * like reading module properties. - * @param string $name application component or property name + * @param string $name component or property name * @return mixed the named property value */ public function __get($name) @@ -142,7 +148,7 @@ abstract class Module extends Component /** * Checks if a property value is null. * This method overrides the parent implementation by checking - * if the named application component is loaded. + * if the named component is loaded. * @param string $name the property name or the event name * @return boolean whether the property value is null */ @@ -163,7 +169,7 @@ abstract class Module extends Component */ public function init() { - \Yii::setAlias('@' . $this->id, $this->getBasePath()); + Yii::setAlias('@' . $this->id, $this->getBasePath()); $this->preloadComponents(); } @@ -282,19 +288,19 @@ abstract class Module extends Component /** * Imports the specified path aliases. * This method is provided so that you can import a set of path aliases when configuring a module. - * The path aliases will be imported by calling [[\Yii::import()]]. + * The path aliases will be imported by calling [[Yii::import()]]. * @param array $aliases list of path aliases to be imported */ public function setImport($aliases) { foreach ($aliases as $alias) { - \Yii::import($alias); + Yii::import($alias); } } /** * Defines path aliases. - * This method calls [[\Yii::setAlias()]] to register the path aliases. + * This method calls [[Yii::setAlias()]] to register the path aliases. * This method is provided so that you can define path aliases when configuring a module. * @param array $aliases list of path aliases to be defined. The array keys are alias names * (must start with '@') and the array values are the corresponding paths or aliases. @@ -302,7 +308,7 @@ abstract class Module extends Component * * ~~~ * array( - * '@models' => '@app/models', // an existing alias + * '@models' => '@application/models', // an existing alias * '@backend' => __DIR__ . '/../backend', // a directory * ) * ~~~ @@ -310,7 +316,7 @@ abstract class Module extends Component public function setAliases($aliases) { foreach ($aliases as $name => $alias) { - \Yii::setAlias($name, $alias); + Yii::setAlias($name, $alias); } } @@ -339,8 +345,8 @@ abstract class Module extends Component if ($this->_modules[$id] instanceof Module) { return $this->_modules[$id]; } elseif ($load) { - \Yii::trace("Loading \"$id\" module", __CLASS__); - return $this->_modules[$id] = \Yii::createObject($this->_modules[$id], $id, $this); + Yii::trace("Loading module: $id", __CLASS__); + return $this->_modules[$id] = Yii::createObject($this->_modules[$id], $id, $this); } } return null; @@ -393,7 +399,7 @@ abstract class Module extends Component * * Each sub-module should be specified as a name-value pair, where * name refers to the ID of the module and value the module or a configuration - * array that can be used to create the module. In the latter case, [[\Yii::createObject()]] + * array that can be used to create the module. In the latter case, [[Yii::createObject()]] * will be used to create the module. * * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently. @@ -423,8 +429,8 @@ abstract class Module extends Component /** * Checks whether the named component exists. - * @param string $id application component ID - * @return boolean whether the named application component exists. Both loaded and unloaded components + * @param string $id component ID + * @return boolean whether the named component exists. Both loaded and unloaded components * are considered. */ public function hasComponent($id) @@ -433,11 +439,10 @@ abstract class Module extends Component } /** - * Retrieves the named application component. - * @param string $id application component ID (case-sensitive) + * Retrieves the named component. + * @param string $id component ID (case-sensitive) * @param boolean $load whether to load the component if it is not yet loaded. - * @return Component|null the application component instance, null if the application component - * does not exist. + * @return Component|null the component instance, null if the component does not exist. * @see hasComponent() */ public function getComponent($id, $load = true) @@ -446,22 +451,22 @@ abstract class Module extends Component if ($this->_components[$id] instanceof Component) { return $this->_components[$id]; } elseif ($load) { - \Yii::trace("Loading \"$id\" application component", __CLASS__); - return $this->_components[$id] = \Yii::createObject($this->_components[$id]); + Yii::trace("Loading component: $id", __CLASS__); + return $this->_components[$id] = Yii::createObject($this->_components[$id]); } } return null; } /** - * Registers an application component in this module. + * Registers a component with this module. * @param string $id component ID - * @param Component|array|null $component the component to be added to the module. This can + * @param Component|array|null $component the component to be registered with the module. This can * be one of the followings: * * - a [[Component]] object * - a configuration array: when [[getComponent()]] is called initially for this component, the array - * will be used to instantiate the component + * will be used to instantiate the component via [[Yii::createObject()]]. * - null: the named component will be removed from the module */ public function setComponent($id, $component) @@ -474,11 +479,11 @@ abstract class Module extends Component } /** - * Returns the application components. + * Returns the registered components. * @param boolean $loadedOnly whether to return the loaded components only. If this is set false, * then all components specified in the configuration will be returned, whether they are loaded or not. * Loaded components will be returned as objects, while unloaded components as configuration arrays. - * @return array the application components (indexed by their IDs) + * @return array the components (indexed by their IDs) */ public function getComponents($loadedOnly = false) { @@ -496,11 +501,11 @@ abstract class Module extends Component } /** - * Registers a set of application components in this module. + * Registers a set of components in this module. * - * Each application component should be specified as a name-value pair, where + * Each component should be specified as a name-value pair, where * name refers to the ID of the component and value the component or a configuration - * array that can be used to create the component. In the latter case, [[\Yii::createObject()]] + * array that can be used to create the component. In the latter case, [[Yii::createObject()]] * will be used to create the component. * * If a new component has the same ID as an existing one, the existing one will be overwritten silently. @@ -520,7 +525,7 @@ abstract class Module extends Component * ) * ~~~ * - * @param array $components application components (id => component configuration or instance) + * @param array $components components (id => component configuration or instance) */ public function setComponents($components) { @@ -530,7 +535,7 @@ abstract class Module extends Component } /** - * Loads application components that are declared in [[preload]]. + * Loads components that are declared in [[preload]]. */ public function preloadComponents() { @@ -540,54 +545,47 @@ abstract class Module extends Component } /** - * Performs a controller action specified by a route. - * This method parses the specified route and creates the corresponding controller and action - * instances under the context of the specified module. It then runs the created action - * with the given parameters. + * Runs a controller action specified by a route. + * This method parses the specified route and creates the corresponding child module(s), controller and action + * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters. + * If the route is empty, the method will use [[defaultRoute]]. * @param string $route the route that specifies the action. * @param array $params the parameters to be passed to the action - * @return integer the action - * @throws InvalidConfigException if the module's defaultRoute is empty or the controller's defaultAction is empty - * @throws InvalidRequestException if the requested route cannot be resolved into an action successfully + * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal. + * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully */ public function runAction($route, $params = array()) { $route = trim($route, '/'); if ($route === '') { $route = trim($this->defaultRoute, '/'); - if ($route == '') { - throw new InvalidConfigException(get_class($this) . '::defaultRoute cannot be empty.'); - } } if (($pos = strpos($route, '/')) !== false) { $id = substr($route, 0, $pos); - $route = substr($route, $pos + 1); + $route2 = substr($route, $pos + 1); } else { $id = $route; - $route = ''; + $route2 = ''; } $module = $this->getModule($id); if ($module !== null) { - return $module->runAction($route, $params); + return $module->runAction($route2, $params); } $controller = $this->createController($id); if ($controller !== null) { - if ($route === '') { - $route = $controller->defaultAction; - if ($route == '') { - throw new InvalidConfigException(get_class($controller) . '::defaultAction cannot be empty.'); - } - } + $oldController = Yii::$application->controller; + Yii::$application->controller = $controller; - $action = $controller->createAction($route); - if ($action !== null) { - return $action->runWithParams($params); - } - } + $status = $controller->runAction($route2, $params); - throw new InvalidRequestException('Unable to resolve the request: ' . ltrim($this->getUniqueId() . '/' . $route, '/')); + Yii::$application->controller = $oldController; + + return $status; + } else { + throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $route); + } } /** diff --git a/framework/base/View.php b/framework/base/View.php index db0741a..9657025 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -97,7 +97,7 @@ class View extends Component * To determine which view file should be rendered, the method calls [[findViewFile()]] which * will search in the directories as specified by [[basePath]]. * - * View name can be a path alias representing an absolute file path (e.g. `@app/views/layout/index`), + * View name can be a path alias representing an absolute file path (e.g. `@application/views/layout/index`), * or a path relative to [[basePath]]. The file suffix is optional and defaults to `.php` if not given * in the view name. * diff --git a/framework/base/Widget.php b/framework/base/Widget.php index 3608205..686e58e 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -80,7 +80,7 @@ class Widget extends Component * To determine which view file should be rendered, the method calls [[findViewFile()]] which * will search in the directories as specified by [[basePath]]. * - * View name can be a path alias representing an absolute file path (e.g. `@app/views/layout/index`), + * View name can be a path alias representing an absolute file path (e.g. `@application/views/layout/index`), * or a path relative to [[basePath]]. The file suffix is optional and defaults to `.php` if not given * in the view name. * diff --git a/framework/logging/DbTarget.php b/framework/logging/DbTarget.php index 004bf21..129e4d4 100644 --- a/framework/logging/DbTarget.php +++ b/framework/logging/DbTarget.php @@ -89,16 +89,17 @@ class DbTarget extends Target } /** - * Stores log [[messages]] to DB. - * @param boolean $final whether this method is called at the end of the current application + * Stores log messages to DB. + * @param array $messages the messages to be exported. See [[Logger::messages]] for the structure + * of each message. */ - public function exportMessages($final) + public function export($messages) { $db = $this->getDb(); $tableName = $db->quoteTableName($this->tableName); $sql = "INSERT INTO $tableName (level, category, log_time, message) VALUES (:level, :category, :log_time, :message)"; $command = $db->createCommand($sql); - foreach ($this->messages as $message) { + foreach ($messages as $message) { $command->bindValues(array( ':level' => $message[1], ':category' => $message[2], diff --git a/framework/logging/EmailTarget.php b/framework/logging/EmailTarget.php index 73fd3bb..e02e4da 100644 --- a/framework/logging/EmailTarget.php +++ b/framework/logging/EmailTarget.php @@ -39,13 +39,14 @@ class EmailTarget extends Target public $headers = array(); /** - * Sends log [[messages]] to specified email addresses. - * @param boolean $final whether this method is called at the end of the current application + * Sends log messages to specified email addresses. + * @param array $messages the messages to be exported. See [[Logger::messages]] for the structure + * of each message. */ - public function exportMessages($final) + public function export($messages) { $body = ''; - foreach ($this->messages as $message) { + foreach ($messages as $message) { $body .= $this->formatMessage($message); } $body = wordwrap($body, 70); diff --git a/framework/logging/FileTarget.php b/framework/logging/FileTarget.php index f4ddf44..0eb897e 100644 --- a/framework/logging/FileTarget.php +++ b/framework/logging/FileTarget.php @@ -65,19 +65,28 @@ class FileTarget extends Target } /** - * Sends log [[messages]] to specified email addresses. - * @param boolean $final whether this method is called at the end of the current application + * Sends log messages to specified email addresses. + * @param array $messages the messages to be exported. See [[Logger::messages]] for the structure + * of each message. */ - public function exportMessages($final) + public function export($messages) { + $text = ''; + foreach ($messages as $message) { + $text .= $this->formatMessage($message); + } + $fp = @fopen($this->logFile, 'a'); + @flock($fp, LOCK_EX); if (@filesize($this->logFile) > $this->maxFileSize * 1024) { $this->rotateFiles(); + @flock($fp,LOCK_UN); + @fclose($fp); + @file_put_contents($this->logFile, $text, FILE_APPEND | LOCK_EX); + } else { + @fwrite($fp, $text); + @flock($fp,LOCK_UN); + @fclose($fp); } - $messages = array(); - foreach ($this->messages as $message) { - $messages[] = $this->formatMessage($message); - } - @file_put_contents($this->logFile, implode('', $messages), FILE_APPEND | LOCK_EX); } /** diff --git a/framework/logging/Logger.php b/framework/logging/Logger.php index c139193..a8ffb5e 100644 --- a/framework/logging/Logger.php +++ b/framework/logging/Logger.php @@ -8,16 +8,13 @@ */ namespace yii\logging; - -use yii\base\Event; -use yii\base\Exception; +use yii\base\InvalidConfigException; /** * Logger records logged messages in memory. * - * When [[flushInterval()]] is reached or when application terminates, it will - * call [[flush()]] to send logged messages to different log targets, such as - * file, email, Web. + * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]] + * to send logged messages to different log targets, such as file, email, Web. * * @author Qiang Xue * @since 2.0 @@ -25,15 +22,6 @@ use yii\base\Exception; class Logger extends \yii\base\Component { /** - * @event Event an event that is triggered when [[flush()]] is called. - */ - const EVENT_FLUSH = 'flush'; - /** - * @event Event an event that is triggered when [[flush()]] is called at the end of application. - */ - const EVENT_FINAL_FLUSH = 'finalFlush'; - - /** * Error message level. An error message is one that indicates the abnormal termination of the * application and may require developer's handling. */ @@ -82,7 +70,7 @@ class Logger extends \yii\base\Component * * ~~~ * array( - * [0] => message (mixed) + * [0] => message (mixed, can be a string or some complex data, such as an exception object) * [1] => level (integer) * [2] => category (string) * [3] => timestamp (float, obtained by microtime(true)) @@ -90,6 +78,10 @@ class Logger extends \yii\base\Component * ~~~ */ public $messages = array(); + /** + * @var Router the log target router registered with this logger. + */ + public $router; /** * Initializes the logger by registering [[flush()]] as a shutdown function. @@ -138,7 +130,9 @@ class Logger extends \yii\base\Component */ public function flush($final = false) { - $this->trigger($final ? self::EVENT_FINAL_FLUSH : self::EVENT_FLUSH); + if ($this->router) { + $this->router->dispatch($this->messages, $final); + } $this->messages = array(); } @@ -149,7 +143,7 @@ class Logger extends \yii\base\Component * of [[YiiBase]] class file. * @return float the total elapsed time in seconds for current request. */ - public function getExecutionTime() + public function getElapsedTime() { return microtime(true) - YII_BEGIN_TIME; } @@ -218,7 +212,7 @@ class Logger extends \yii\base\Component if (($last = array_pop($stack)) !== null && $last[0] === $token) { $timings[] = array($token, $category, $timestamp - $last[3]); } else { - throw new Exception("Unmatched profiling block: $token"); + throw new InvalidConfigException("Unmatched profiling block: $token"); } } } @@ -231,5 +225,4 @@ class Logger extends \yii\base\Component return $timings; } - } diff --git a/framework/logging/Router.php b/framework/logging/Router.php index 75fbbc0..2e6a8dd 100644 --- a/framework/logging/Router.php +++ b/framework/logging/Router.php @@ -81,26 +81,21 @@ class Router extends Component $this->targets[$name] = Yii::createObject($target); } } - - Yii::getLogger()->on(Logger::EVENT_FLUSH, array($this, 'processMessages')); - Yii::getLogger()->on(Logger::EVENT_FINAL_FLUSH, array($this, 'processMessages')); + Yii::getLogger()->router = $this; } /** - * Retrieves and processes log messages from the system logger. - * This method mainly serves the event handler to the [[Logger::EVENT_FLUSH]] event - * and the [[Logger::EVENT_FINAL_FLUSH]] event. - * It will retrieve the available log messages from the [[Yii::getLogger()|system logger]] - * and invoke the registered [[targets|log targets]] to do the actual processing. - * @param \yii\base\Event $event event parameter + * Dispatches log messages to [[targets]]. + * This method is called by [[Logger]] when its [[Logger::flush()]] method is called. + * It will forward the messages to each log target registered in [[targets]]. + * @param array $messages the messages to be processed + * @param boolean $final whether this is the final call during a request cycle */ - public function processMessages($event) + public function dispatch($messages, $final = false) { - $messages = Yii::getLogger()->messages; - $final = $event->name === Logger::EVENT_FINAL_FLUSH; foreach ($this->targets as $target) { if ($target->enabled) { - $target->processMessages($messages, $final); + $target->collect($messages, $final); } } } diff --git a/framework/logging/Target.php b/framework/logging/Target.php index a4e7714..c9e175a 100644 --- a/framework/logging/Target.php +++ b/framework/logging/Target.php @@ -50,15 +50,6 @@ abstract class Target extends \yii\base\Component */ public $except = array(); /** - * @var boolean whether to prefix each log message with the current session ID. Defaults to false. - */ - public $prefixSession = false; - /** - * @var boolean whether to prefix each log message with the current user name and ID. Defaults to false. - * @see \yii\web\User - */ - public $prefixUser = false; - /** * @var boolean whether to log a message containing the current user name and ID. Defaults to false. * @see \yii\web\User */ @@ -77,19 +68,18 @@ abstract class Target extends \yii\base\Component public $exportInterval = 1000; /** * @var array the messages that are retrieved from the logger so far by this log target. - * @see autoExport */ - public $messages = array(); + private $_messages = array(); private $_levels = 0; /** * Exports log messages to a specific destination. - * Child classes must implement this method. Note that you may need - * to clean up [[messages]] in this method to avoid re-exporting messages. - * @param boolean $final whether this method is called at the end of the current application + * Child classes must implement this method. + * @param array $messages the messages to be exported. See [[Logger::messages]] for the structure + * of each message. */ - abstract public function exportMessages($final); + abstract public function export($messages); /** * Processes the given log messages. @@ -99,45 +89,16 @@ abstract class Target extends \yii\base\Component * of each message. * @param boolean $final whether this method is called at the end of the current application */ - public function processMessages($messages, $final) + public function collect($messages, $final) { - $messages = $this->filterMessages($messages); - $this->messages = array_merge($this->messages, $messages); - - $count = count($this->messages); + $this->_messages = array($this->_messages, $this->filterMessages($messages)); + $count = count($this->_messages); if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) { - $this->prepareExport($final); - $this->exportMessages($final); - $this->messages = array(); - } - } - - /** - * Prepares the [[messages]] for exporting. - * This method will modify each message by prepending extra information - * if [[prefixSession]] and/or [[prefixUser]] are set true. - * It will also add an additional message showing context information if - * [[logUser]] and/or [[logVars]] are set. - * @param boolean $final whether this method is called at the end of the current application - */ - protected function prepareExport($final) - { - $prefix = array(); - if ($this->prefixSession && ($id = session_id()) !== '') { - $prefix[] = "[$id]"; - } - if ($this->prefixUser && ($user = \Yii::$application->getComponent('user', false)) !== null) { - $prefix[] = '[' . $user->getName() . ']'; - $prefix[] = '[' . $user->getId() . ']'; - } - if ($prefix !== array()) { - $prefix = implode(' ', $prefix); - foreach ($this->messages as $i => $message) { - $this->messages[$i][0] = $prefix . ' ' . $this->messages[$i][0]; + if (($context = $this->getContextMessage()) !== '') { + $this->_messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME); } - } - if ($final && ($context = $this->getContextMessage()) !== '') { - $this->messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME); + $this->export($this->_messages); + $this->_messages = array(); } } @@ -164,7 +125,7 @@ abstract class Target extends \yii\base\Component /** * @return integer the message levels that this target is interested in. This is a bitmap of - * level values. Defaults to 0, meaning all available levels. + * level values. Defaults to 0, meaning all available levels. */ public function getLevels() { diff --git a/framework/util/FileHelper.php b/framework/util/FileHelper.php index b0b0611..d340338 100644 --- a/framework/util/FileHelper.php +++ b/framework/util/FileHelper.php @@ -10,6 +10,7 @@ namespace yii\util; use yii\base\Exception; +use yii\base\InvalidConfigException; /** * Filesystem helper @@ -37,7 +38,7 @@ class FileHelper * If the given path does not refer to an existing directory, an exception will be thrown. * @param string $path the given path. This can also be a path alias. * @return string the normalized path - * @throws Exception if the path does not refer to an existing directory. + * @throws InvalidConfigException if the path does not refer to an existing directory. */ public static function ensureDirectory($path) { @@ -45,7 +46,7 @@ class FileHelper if ($p !== false && ($p = realpath($p)) !== false && is_dir($p)) { return $p; } else { - throw new Exception('Directory does not exist: ' . $path); + throw new InvalidConfigException('Directory does not exist: ' . $path); } } From 0d21ee67cb19d2d71ad44f5e55ea46e4681239c0 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Mon, 28 Jan 2013 18:51:36 -0500 Subject: [PATCH 05/14] MVC WIP --- framework/base/Action.php | 41 +++++++++++++++++++----- framework/base/Controller.php | 40 +++++------------------ framework/base/InlineAction.php | 31 +++++++++++------- framework/console/Application.php | 25 +-------------- framework/console/Controller.php | 27 ++++++++++++++++ framework/console/controllers/HelpController.php | 2 +- 6 files changed, 90 insertions(+), 76 deletions(-) diff --git a/framework/base/Action.php b/framework/base/Action.php index 1948c9d..6925500 100644 --- a/framework/base/Action.php +++ b/framework/base/Action.php @@ -53,18 +53,43 @@ class Action extends Component * This method is mainly invoked by the controller. * @param array $params action parameters * @return integer the exit status (0 means normal, non-zero means abnormal). + * @throws InvalidConfigException if the action class does not have a run() method */ public function runWithParams($params) { - try { - $ps = ReflectionHelper::extractMethodParams($this, 'run', $params); - } catch (Exception $e) { - $this->controller->invalidActionParams($this, $e); - return 1; + if (!method_exists($this, 'run')) { + throw new InvalidConfigException(get_class($this) . ' must define a "run()" method.'); } - if ($params !== $ps) { - $this->controller->extraActionParams($this, $ps, $params); + $method = new \ReflectionMethod($this, 'run'); + $args = $this->bindActionParams($method, $params); + return (int)$method->invokeArgs($this, $args); + } + + /** + * Binds the given parameters to the action method. + * The returned array contains the parameters that need to be passed to the action method. + * This method calls [[Controller::validateActionParams()]] to check if any exception + * should be raised if there are missing or unknown parameters. + * @param \ReflectionMethod $method the action method reflection object + * @param array $params the supplied parameters + * @return array the parameters that can be passed to the action method + */ + protected function bindActionParams($method, $params) + { + $args = array(); + $missing = array(); + foreach ($method->getParameters() as $param) { + $name = $param->getName(); + if (array_key_exists($name, $params)) { + $args[] = $params[$name]; + unset($params[$name]); + } elseif ($param->isDefaultValueAvailable()) { + $args[] = $param->getDefaultValue(); + } else { + $missing[] = $name; + } } - return (int)call_user_func_array(array($this, 'run'), $ps); + $this->controller->validateActionParams($this, $missing, $params); + return $args; } } diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 79ad574..39c829d 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -190,7 +190,7 @@ class Controller extends Component if (method_exists($this, $methodName)) { $method = new \ReflectionMethod($this, $methodName); if ($method->getName() === $methodName) { - return new InlineAction($id, $this); + return new InlineAction($id, $this, $methodName); } } } @@ -245,39 +245,15 @@ class Controller extends Component } /** - * This method is invoked when the request parameters do not satisfy the requirement of the specified action. - * The default implementation will throw an exception. - * @param Action $action the action being executed - * @param Exception $exception the exception about the invalid parameters - * @throws Exception whenever this method is invoked + * Validates the parameter being bound to actions. + * This method is invoked when parameters are being bound to the currently requested action. + * Child classes may override this method to throw exceptions when there are missing and/or unknown parameters. + * @param Action $action the currently requested action + * @param array $missingParams the names of the missing parameters + * @param array $unknownParams the unknown parameters (name=>value) */ - public function invalidActionParams($action, $exception) + public function validateActionParams($action, $missingParams, $unknownParams) { - throw $exception; - } - - /** - * This method is invoked when extra parameters are provided to an action when it is executed. - * The default implementation does nothing. - * @param Action $action the action being executed - * @param array $expected the expected action parameters (name => value) - * @param array $actual the actual action parameters (name => value) - */ - public function extraActionParams($action, $expected, $actual) - { - } - - /** - * Handles the request whose action is not recognized. - * This method is invoked when the controller cannot find the requested action. - * The default implementation simply throws an exception. - * @param string $actionID the missing action name - * @throws InvalidRequestException whenever this method is invoked - */ - public function missingAction($actionID) - { - throw new InvalidRequestException(\Yii::t('yii', 'The system is unable to find the requested action "{action}".', - array('{action}' => $actionID == '' ? $this->defaultAction : $actionID))); } /** diff --git a/framework/base/InlineAction.php b/framework/base/InlineAction.php index 8764ac2..4c509a3 100644 --- a/framework/base/InlineAction.php +++ b/framework/base/InlineAction.php @@ -23,6 +23,23 @@ use yii\util\ReflectionHelper; class InlineAction extends Action { /** + * @var string the controller method that this inline action is associated with + */ + public $actionMethod; + + /** + * @param string $id the ID of this action + * @param Controller $controller the controller that owns this action + * @param string $actionMethod the controller method that this inline action is associated with + * @param array $config name-value pairs that will be used to initialize the object properties + */ + public function __construct($id, $controller, $actionMethod, $config = array()) + { + $this->actionMethod = $actionMethod; + parent::__construct($id, $controller, $config); + } + + /** * Runs this action with the specified parameters. * This method is mainly invoked by the controller. * @param array $params action parameters @@ -30,16 +47,8 @@ class InlineAction extends Action */ public function runWithParams($params) { - try { - $method = 'action' . $this->id; - $ps = ReflectionHelper::extractMethodParams($this->controller, $method, $params); - } catch (Exception $e) { - $this->controller->invalidActionParams($this, $e); - return 1; - } - if ($params !== $ps) { - $this->controller->extraActionParams($this, $ps, $params); - } - return (int)call_user_func_array(array($this->controller, $method), $ps); + $method = new \ReflectionMethod($this->controller, $this->actionMethod); + $args = $this->bindActionParams($method, $params); + return (int)$method->invokeArgs($this, $args); } } diff --git a/framework/console/Application.php b/framework/console/Application.php index 23d80e0..1b3192e 100644 --- a/framework/console/Application.php +++ b/framework/console/Application.php @@ -92,36 +92,13 @@ class Application extends \yii\base\Application /** @var $request Request */ $request = $this->getRequest(); if ($request->getIsConsoleRequest()) { - return $this->runController($request->route, $request->params); + return $this->runAction($request->route, $request->params); } else { die('This script must be run from the command line.'); } } /** - * Runs a controller with the given route and parameters. - * @param string $route the route (e.g. `post/create`) - * @param array $params the parameters to be passed to the controller action - * @return integer the exit status (0 means normal, non-zero values mean abnormal) - * @throws Exception if the route cannot be resolved into a controller - */ - public function runController($route, $params = array()) - { - $result = $this->createController($route); - if ($result === false) { - throw new Exception(\Yii::t('yii', 'Unable to resolve the request.')); - } - /** @var $controller \yii\console\Controller */ - list($controller, $action) = $result; - $priorController = $this->controller; - $this->controller = $controller; - $params = ReflectionHelper::initObjectWithParams($controller, $params); - $status = $controller->run($action, $params); - $this->controller = $priorController; - return $status; - } - - /** * Returns the configuration of the built-in commands. * @return array the configuration of the built-in commands. */ diff --git a/framework/console/Controller.php b/framework/console/Controller.php index 250cefe..164f631 100644 --- a/framework/console/Controller.php +++ b/framework/console/Controller.php @@ -10,6 +10,7 @@ namespace yii\console; use yii\base\Action; +use yii\base\InvalidRouteException; use yii\base\Exception; /** @@ -30,6 +31,32 @@ use yii\base\Exception; class Controller extends \yii\base\Controller { /** + * 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. + * @see createAction + */ + public function runAction($id, $params = array()) + { + if ($params !== array()) { + $class = new \ReflectionClass($this); + foreach ($params as $name => $value) { + if ($class->hasProperty($name)) { + $property = $class->getProperty($name); + if ($property->isPublic() && !$property->isStatic() && $property->getDeclaringClass()->getName() === get_class($this)) { + $this->$name = $value; + unset($params[$name]); + } + } + } + } + return parent::runAction($id, $params); + } + + /** * This method is invoked when the request parameters do not satisfy the requirement of the specified action. * The default implementation will throw an exception. * @param Action $action the action being executed diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index f4d1eb8..5617c7b 100644 --- a/framework/console/controllers/HelpController.php +++ b/framework/console/controllers/HelpController.php @@ -312,7 +312,7 @@ class HelpController extends Controller { $options = array(); foreach ($class->getProperties() as $property) { - if (!$property->isPublic() || $property->isStatic() || $property->getDeclaringClass()->getName() === 'yii\base\Controller') { + if (!$property->isPublic() || $property->isStatic() || $property->getDeclaringClass()->getName() !== get_class($controller)) { continue; } $name = $property->getName(); From 9165a1592a499c6a67610ee90815ecb0d1c83a11 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Tue, 29 Jan 2013 09:01:38 -0500 Subject: [PATCH 06/14] cleanup. --- framework/base/Action.php | 13 +++- framework/base/ActionEvent.php | 7 +- framework/base/ActionFilter.php | 90 ------------------------ framework/base/Controller.php | 29 +++----- framework/base/ErrorHandler.php | 11 +-- framework/base/Exception.php | 4 ++ framework/base/InlineAction.php | 6 +- framework/base/InvalidCallException.php | 4 ++ framework/base/InvalidConfigException.php | 4 ++ framework/base/InvalidRequestException.php | 4 ++ framework/base/InvalidRouteException.php | 4 ++ framework/base/Module.php | 11 +-- framework/base/NotSupportedException.php | 4 ++ framework/base/UnknownMethodException.php | 4 ++ framework/base/UnknownPropertyException.php | 4 ++ framework/db/Exception.php | 5 ++ framework/util/ReflectionHelper.php | 103 ---------------------------- 17 files changed, 69 insertions(+), 238 deletions(-) delete mode 100644 framework/base/ActionFilter.php delete mode 100644 framework/util/ReflectionHelper.php diff --git a/framework/base/Action.php b/framework/base/Action.php index 6925500..8d4ec5a 100644 --- a/framework/base/Action.php +++ b/framework/base/Action.php @@ -9,8 +9,6 @@ namespace yii\base; -use yii\util\ReflectionHelper; - /** * Action is the base class for all controller action classes. * @@ -21,6 +19,14 @@ use yii\util\ReflectionHelper; * will be invoked by the controller when the action is requested. * The `run()` method can have parameters which will be filled up * with user input values automatically according to their names. + * For example, if the `run()` method is declared as follows: + * + * ~~~ + * public function run($id, $type = 'book') { ... } + * ~~~ + * + * And the parameters provided for the action are: `array('id' => 1)`. + * Then the `run()` method will be invoked as `run(1)` automatically. * * @author Qiang Xue * @since 2.0 @@ -37,6 +43,7 @@ class Action extends Component public $controller; /** + * Constructor. * @param string $id the ID of this action * @param Controller $controller the controller that owns this action * @param array $config name-value pairs that will be used to initialize the object properties @@ -51,7 +58,7 @@ class Action extends Component /** * Runs this action with the specified parameters. * This method is mainly invoked by the controller. - * @param array $params action parameters + * @param array $params the parameters to be bound to the action's run() method. * @return integer the exit status (0 means normal, non-zero means abnormal). * @throws InvalidConfigException if the action class does not have a run() method */ diff --git a/framework/base/ActionEvent.php b/framework/base/ActionEvent.php index 1b3e07d..ee945a8 100644 --- a/framework/base/ActionEvent.php +++ b/framework/base/ActionEvent.php @@ -12,8 +12,7 @@ namespace yii\base; /** * ActionEvent represents the event parameter used for an action event. * - * By setting the [[isValid]] property, one may control whether to continue the life cycle of - * the action currently being executed. + * By setting the [[isValid]] property, one may control whether to continue running the action. * * @author Qiang Xue * @since 2.0 @@ -25,7 +24,7 @@ class ActionEvent extends Event */ public $action; /** - * @var boolean whether the action is in valid state and its life cycle should proceed. + * @var boolean whether to continue running the action. */ public $isValid = true; @@ -34,7 +33,7 @@ class ActionEvent extends Event * @param Action $action the action associated with this action event. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct(Action $action, $config = array()) + public function __construct($action, $config = array()) { $this->action = $action; parent::__construct($config); diff --git a/framework/base/ActionFilter.php b/framework/base/ActionFilter.php deleted file mode 100644 index 9cb5331..0000000 --- a/framework/base/ActionFilter.php +++ /dev/null @@ -1,90 +0,0 @@ - - * @since 2.0 - */ -class ActionFilter extends Behavior -{ - /** - * @var Controller the owner of this behavior. For action filters, this should be a controller object. - */ - public $owner; - /** - * @var array IDs of actions that this filter applies to. - * If this property is empty or not set, it means this filter applies to all actions. - * Note that if an action appears in [[except]], the filter will not apply to this action, even - * if the action also appears in [[only]]. - * @see exception - */ - public $only; - /** - * @var array IDs of actions that this filter does NOT apply to. - */ - public $except; - - public function init() - { - $this->owner->on('authorize', array($this, 'handleEvent')); - $this->owner->on('beforeAction', array($this, 'handleEvent')); - $this->owner->on('beforeRender', array($this, 'handleEvent')); - $this->owner->getEventHandlers('afterRender')->insertAt(0, array($this, 'handleEvent')); - $this->owner->getEventHandlers('afterAction')->insertAt(0, array($this, 'handleEvent')); - } - - public function authorize($event) - { - } - - public function beforeAction($event) - { - } - - public function beforeRender($event) - { - } - - public function afterRender($event) - { - } - - public function afterAction($event) - { - } - - public function handleEvent($event) - { - if ($this->applyTo($event->action)) { - $this->{$event->name}($event); - } - } - - public function applyTo(Action $action) - { - return (empty($this->only) || in_array($action->id, $this->only, false) !== false) - && (empty($this->except) || in_array($action->id, $this->except, false) === false); - } -} \ No newline at end of file diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 39c829d..5b7b460 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -15,13 +15,6 @@ use yii\util\StringHelper; /** * Controller is the base class for classes containing controller logic. * - * Controller implements the action life cycles, which consist of the following steps: - * - * 1. [[authorize]] - * 2. [[beforeAction]] - * 3. [[afterAction]] - * - * @property array $actionParams the request parameters (name-value pairs) to be used for action parameter binding * @property string $route the route (module ID, controller ID and action ID) of the current request. * @property string $uniqueId the controller ID that is prefixed with the module ID (if any). * @@ -30,7 +23,6 @@ use yii\util\StringHelper; */ class Controller extends Component { - const EVENT_AUTHORIZE = 'authorize'; const EVENT_BEFORE_ACTION = 'beforeAction'; const EVENT_AFTER_ACTION = 'afterAction'; @@ -117,7 +109,7 @@ class Controller extends Component $oldAction = $this->action; $this->action = $action; - if ($this->authorize($action) && $this->beforeAction($action)) { + if ($this->beforeAction($action)) { $status = $action->runWithParams($params); $this->afterAction($action); } else { @@ -198,18 +190,6 @@ class Controller extends Component } /** - * This method is invoked when checking the access for the action to be executed. - * @param Action $action the action to be executed. - * @return boolean whether the action is allowed to be executed. - */ - public function authorize($action) - { - $event = new ActionEvent($action); - $this->trigger(self::EVENT_AUTHORIZE, $event); - return $event->isValid; - } - - /** * This method is invoked right before an action is to be executed (after all possible filters.) * You may override this method to do last-minute preparation for the action. * @param Action $action the action to be executed. @@ -273,6 +253,13 @@ class Controller extends Component return $this->action !== null ? $this->getUniqueId() . '/' . $this->action->id : $this->getUniqueId(); } + /** + * Renders a view and applies layout if available. + * + * @param $view + * @param array $params + * @return string + */ public function render($view, $params = array()) { return $this->createView()->render($view, $params); diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index 9f1621a..c17755e 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -52,11 +52,7 @@ class ErrorHandler extends Component * @var \Exception the exception that is being handled currently */ public $exception; - /** - * @var boolean whether to log errors also using error_log(). Defaults to true. - * Note that errors captured by the error handler are always logged by [[\Yii::error()]]. - */ - public $logErrors = true; + public function init() { @@ -123,7 +119,7 @@ class ErrorHandler extends Component protected function render($exception) { if ($this->errorAction !== null) { - \Yii::$application->runController($this->errorAction); + \Yii::$application->runAction($this->errorAction); } elseif (\Yii::$application instanceof \yii\web\Application) { if (!headers_sent()) { $errorCode = $exception instanceof HttpException ? $exception->statusCode : 500; @@ -297,9 +293,6 @@ class ErrorHandler extends Component $category .= '\\' . $exception->getSeverity(); } \Yii::error((string)$exception, $category); - if ($this->logErrors) { - error_log($exception); - } } public function clearOutput() diff --git a/framework/base/Exception.php b/framework/base/Exception.php index a740a35..89fa30a 100644 --- a/framework/base/Exception.php +++ b/framework/base/Exception.php @@ -17,5 +17,9 @@ namespace yii\base; */ class Exception extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Exception'; } diff --git a/framework/base/InlineAction.php b/framework/base/InlineAction.php index 4c509a3..00ecb8f 100644 --- a/framework/base/InlineAction.php +++ b/framework/base/InlineAction.php @@ -9,13 +9,11 @@ namespace yii\base; -use yii\util\ReflectionHelper; - /** * InlineAction represents an action that is defined as a controller method. * - * The name of the controller method should be in the format of `actionXyz` - * where `Xyz` stands for the action ID (e.g. `actionIndex`). + * The name of the controller method is available via [[actionMethod]] which + * is set by the [[controller]] who creates this action. * * @author Qiang Xue * @since 2.0 diff --git a/framework/base/InvalidCallException.php b/framework/base/InvalidCallException.php index 24e7b6e..e9d81b4 100644 --- a/framework/base/InvalidCallException.php +++ b/framework/base/InvalidCallException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class InvalidCallException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Invalid Call Exception'; } diff --git a/framework/base/InvalidConfigException.php b/framework/base/InvalidConfigException.php index 5256d7e..8f292df 100644 --- a/framework/base/InvalidConfigException.php +++ b/framework/base/InvalidConfigException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class InvalidConfigException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Invalid Configuration Exception'; } diff --git a/framework/base/InvalidRequestException.php b/framework/base/InvalidRequestException.php index 2e2a04a..38c4115 100644 --- a/framework/base/InvalidRequestException.php +++ b/framework/base/InvalidRequestException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class InvalidRequestException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Invalid Request Exception'; } diff --git a/framework/base/InvalidRouteException.php b/framework/base/InvalidRouteException.php index 8e82b40..6549c07 100644 --- a/framework/base/InvalidRouteException.php +++ b/framework/base/InvalidRouteException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class InvalidRouteException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Invalid Route Exception'; } diff --git a/framework/base/Module.php b/framework/base/Module.php index 23bd577..966cc64 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -27,6 +27,9 @@ use yii\util\FileHelper; * @property string $uniqueId An ID that uniquely identifies this module among all modules within * the current application. * @property string $basePath The root directory of the module. Defaults to the directory containing the module class. + * @property string $controllerPath The directory containing the controller classes. Defaults to "[[basePath]]/controllers". + * @property string $viewPath The directory containing the view files within this module. Defaults to "[[basePath]]/views". + * @property string $layoutPath The directory containing the layout view files within this module. Defaults to "[[viewPath]]/layouts". * @property array $modules The configuration of the currently installed modules (module ID => configuration). * @property array $components The components (indexed by their IDs) registered within this module. * @property array $import List of aliases to be imported. This property is write-only. @@ -240,8 +243,8 @@ abstract class Module extends Component } /** - * @return string the root directory of view files. Defaults to 'moduleDir/views' where - * moduleDir is the directory containing the module class. + * Returns the directory that contains the view files for this module. + * @return string the root directory of view files. Defaults to "[[basePath]]/view". */ public function getViewPath() { @@ -263,8 +266,8 @@ abstract class Module extends Component } /** - * @return string the root directory of layout files. Defaults to 'moduleDir/views/layouts' where - * moduleDir is the directory containing the module class. + * Returns the directory that contains layout view files for this module. + * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts". */ public function getLayoutPath() { diff --git a/framework/base/NotSupportedException.php b/framework/base/NotSupportedException.php index aa2badb..2da008c 100644 --- a/framework/base/NotSupportedException.php +++ b/framework/base/NotSupportedException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class NotSupportedException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Not Supported Exception'; } diff --git a/framework/base/UnknownMethodException.php b/framework/base/UnknownMethodException.php index 8667d24..b88d97f 100644 --- a/framework/base/UnknownMethodException.php +++ b/framework/base/UnknownMethodException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class UnknownMethodException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Unknown Method Exception'; } diff --git a/framework/base/UnknownPropertyException.php b/framework/base/UnknownPropertyException.php index 69581f9..601ae28 100644 --- a/framework/base/UnknownPropertyException.php +++ b/framework/base/UnknownPropertyException.php @@ -17,5 +17,9 @@ namespace yii\base; */ class UnknownPropertyException extends \Exception { + /** + * @var string the user-friend name of this exception + */ + public $name = 'Unknown Property Exception'; } diff --git a/framework/db/Exception.php b/framework/db/Exception.php index bdc1277..61a8e58 100644 --- a/framework/db/Exception.php +++ b/framework/db/Exception.php @@ -18,6 +18,11 @@ namespace yii\db; class Exception extends \yii\base\Exception { /** + * @var string the user-friend name of this exception + */ + public $name = 'Database Exception'; + + /** * @var mixed the error info provided by a PDO exception. This is the same as returned * by [PDO::errorInfo](http://www.php.net/manual/en/pdo.errorinfo.php). */ diff --git a/framework/util/ReflectionHelper.php b/framework/util/ReflectionHelper.php deleted file mode 100644 index cc13f94..0000000 --- a/framework/util/ReflectionHelper.php +++ /dev/null @@ -1,103 +0,0 @@ - - * @since 2.0 - */ -class ReflectionHelper -{ - /** - * Prepares parameters so that they can be bound to the specified method. - * This method converts the input parameters into an array that can later be - * passed to `call_user_func_array()` when calling the specified method. - * The conversion is based on the matching of method parameter names - * and the input array keys. For example, - * - * ~~~ - * class Foo { - * function bar($a, $b) { ... } - * } - * $object = new Foo; - * $params = array('b' => 2, 'c' => 3, 'a' => 1); - * var_export(ReflectionHelper::extractMethodParams($object, 'bar', $params)); - * // output: array('a' => 1, 'b' => 2); - * ~~~ - * - * @param object|string $object the object or class name that owns the specified method - * @param string $method the method name - * @param array $params the parameters in terms of name-value pairs - * @return array parameters that are needed by the method only and - * can be passed to the method via `call_user_func_array()`. - * @throws Exception if any required method parameter is not found in the given parameters - */ - public static function extractMethodParams($object, $method, $params) - { - $m = new \ReflectionMethod($object, $method); - $ps = array(); - foreach ($m->getParameters() as $param) { - $name = $param->getName(); - if (array_key_exists($name, $params)) { - $ps[$name] = $params[$name]; - } elseif ($param->isDefaultValueAvailable()) { - $ps[$name] = $param->getDefaultValue(); - } else { - throw new Exception(\Yii::t('yii', 'Missing required parameter "{name}".', array('{name}' => $name))); - } - } - return $ps; - } - - /** - * Initializes an object with the given parameters. - * Only the public non-static properties of the object will be initialized, and their names must - * match the given parameter names. For example, - * - * ~~~ - * class Foo { - * public $a; - * protected $b; - * } - * $object = new Foo; - * $params = array('b' => 2, 'c' => 3, 'a' => 1); - * $remaining = ReflectionHelper::bindObjectParams($object, $params); - * var_export($object); // output: $object->a = 1; $object->b = null; - * var_export($remaining); // output: array('b' => 2, 'c' => 3); - * ~~~ - * - * @param object $object the object whose properties are to be initialized - * @param array $params the input parameters to be used to initialize the object - * @return array the remaining unused input parameters - */ - public static function initObjectWithParams($object, $params) - { - if (empty($params)) { - return array(); - } - - $class = new \ReflectionClass(get_class($object)); - foreach ($params as $name => $value) { - if ($class->hasProperty($name)) { - $property = $class->getProperty($name); - if ($property->isPublic() && !$property->isStatic()) { - $object->$name = $value; - unset($params[$name]); - } - } - } - - return $params; - } -} From bd320533ab85e45333ad1222a37787c52119bed8 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Wed, 30 Jan 2013 19:49:38 -0500 Subject: [PATCH 07/14] MVC WIP --- framework/YiiBase.php | 19 +-- framework/base/Controller.php | 11 ++ framework/base/ErrorHandler.php | 2 +- framework/base/Theme.php | 105 +++++++++++--- framework/base/View.php | 302 +++++++++++++++++++--------------------- framework/base/Widget.php | 12 ++ framework/util/FileHelper.php | 14 ++ 7 files changed, 272 insertions(+), 193 deletions(-) diff --git a/framework/YiiBase.php b/framework/YiiBase.php index 1230053..14e0f44 100644 --- a/framework/YiiBase.php +++ b/framework/YiiBase.php @@ -8,9 +8,8 @@ */ use yii\base\Exception; -use yii\logging\Logger; -use yii\base\InvalidCallException; use yii\base\InvalidConfigException; +use yii\logging\Logger; /** * Gets the application start timestamp. @@ -189,14 +188,14 @@ class YiiBase * * Note, this method does not ensure the existence of the resulting path. * @param string $alias alias - * @param boolean $throwException whether to throw exception if the alias is invalid. * @return string|boolean path corresponding to the alias, false if the root alias is not previously registered. - * @throws Exception if the alias is invalid and $throwException is true. * @see setAlias */ - public static function getAlias($alias, $throwException = false) + public static function getAlias($alias) { - if (isset(self::$aliases[$alias])) { + if (!is_string($alias)) { + return false; + } elseif (isset(self::$aliases[$alias])) { return self::$aliases[$alias]; } elseif ($alias === '' || $alias[0] !== '@') { // not an alias return $alias; @@ -206,11 +205,7 @@ class YiiBase return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos); } } - if ($throwException) { - throw new Exception("Invalid path alias: $alias"); - } else { - return false; - } + return false; } /** @@ -361,7 +356,7 @@ class YiiBase $class = $config['class']; unset($config['class']); } else { - throw new InvalidCallException('Object configuration must be an array containing a "class" element.'); + throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); } if (!class_exists($class, false)) { diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 5b7b460..d8cfbd2 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -279,4 +279,15 @@ class Controller extends Component { return new View($this); } + + /** + * Returns the directory containing view files for this controller. + * The default implementation returns the directory named as controller [[id]] under the [[module]]'s + * [[viewPath]] directory. + * @return string the directory containing the view files for this controller. + */ + public function getViewPath() + { + return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id; + } } diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index c17755e..23b5d57 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -321,7 +321,7 @@ class ErrorHandler extends Component public function renderAsHtml($exception) { $view = new View; - $view->context = $this; + $view->_owner = $this; $name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView; echo $view->render($name, array( 'exception' => $exception, diff --git a/framework/base/Theme.php b/framework/base/Theme.php index c1fc94a..03f8f55 100644 --- a/framework/base/Theme.php +++ b/framework/base/Theme.php @@ -9,55 +9,114 @@ namespace yii\base; +use Yii; use yii\base\InvalidConfigException; +use yii\util\FileHelper; /** * Theme represents an application theme. * + * A theme is directory consisting of view and layout files which are meant to replace their + * non-themed counterparts. + * + * Theme uses [[pathMap]] to achieve the file replacement. A view or layout file will be replaced + * with its themed version if part of its path matches one of the keys in [[pathMap]]. + * Then the matched part will be replaced with the corresponding array value. + * + * For example, if [[pathMap]] is `array('/www/views' => '/www/themes/basic')`, + * then the themed version for a view file `/www/views/site/index.php` will be + * `/www/themes/basic/site/index.php`. + * + * @property string $baseUrl the base URL for this theme. This is mainly used by [[getUrl()]]. + * * @author Qiang Xue * @since 2.0 */ class Theme extends Component { + /** + * @var string the root path of this theme. + * @see pathMap + */ public $basePath; - public $baseUrl; + /** + * @var array the mapping between view directories and their corresponding themed versions. + * If not set, it will be initialized as a mapping from [[Application::basePath]] to [[basePath]]. + * This property is used by [[apply()]] when a view is trying to apply the theme. + */ + public $pathMap; + + private $_baseUrl; + /** + * Initializes the theme. + * @throws InvalidConfigException if [[basePath]] is not set. + */ public function init() { - if ($this->basePath !== null) { - $this->basePath = \Yii::getAlias($this->basePath, true); - } else { - throw new InvalidConfigException("Theme.basePath must be set."); + parent::init(); + if (empty($this->pathMap)) { + if ($this->basePath !== null) { + $this->basePath = FileHelper::ensureDirectory($this->basePath); + $this->pathMap = array(Yii::$application->getBasePath() => $this->basePath); + } else { + throw new InvalidConfigException("Theme::basePath must be set."); + } } - if ($this->baseUrl !== null) { - $this->baseUrl = \Yii::getAlias($this->baseUrl, true); - } else { - throw new InvalidConfigException("Theme.baseUrl must be set."); + $paths = array(); + foreach ($this->pathMap as $from => $to) { + $paths[FileHelper::normalizePath($from) . DIRECTORY_SEPARATOR] = FileHelper::normalizePath($to) . DIRECTORY_SEPARATOR; } + $this->pathMap = $paths; + } + + /** + * Returns the base URL for this theme. + * The method [[getUrl()]] will prefix this to the given URL. + * @return string the base URL for this theme. + */ + public function getBaseUrl() + { + return $this->_baseUrl; + } + + /** + * Sets the base URL for this theme. + * @param string $value the base URL for this theme. + */ + public function setBaseUrl($value) + { + $this->_baseUrl = rtrim(Yii::getAlias($value), '/'); } /** - * @param Application|Module|Controller|Object $context - * @return string + * Converts a file to a themed file if possible. + * If there is no corresponding themed file, the original file will be returned. + * @param string $path the file to be themed + * @return string the themed file, or the original file if the themed version is not available. */ - public function getViewPath($context = null) + public function apply($path) { - $viewPath = $this->basePath . DIRECTORY_SEPARATOR . 'views'; - if ($context === null || $context instanceof Application) { - return $viewPath; - } elseif ($context instanceof Controller || $context instanceof Module) { - return $viewPath . DIRECTORY_SEPARATOR . $context->getUniqueId(); - } else { - return $viewPath . DIRECTORY_SEPARATOR . str_replace('\\', '_', get_class($context)); + $path = FileHelper::normalizePath($path); + foreach ($this->pathMap as $from => $to) { + if (strpos($path, $from) === 0) { + $n = strlen($from); + $file = $to . substr($path, $n); + if (is_file($file)) { + return $file; + } + } } + return $path; } /** - * @param Module $module - * @return string + * Converts a relative URL into an absolute URL using [[basePath]]. + * @param string $url the relative URL to be converted. + * @return string the absolute URL */ - public function getLayoutPath($module = null) + public function getUrl($url) { - return $this->getViewPath($module) . DIRECTORY_SEPARATOR . 'layouts'; + return $this->baseUrl . '/' . ltrim($url, '/'); } } diff --git a/framework/base/View.php b/framework/base/View.php index 9657025..f4dd07b 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -9,27 +9,26 @@ namespace yii\base; +use Yii; use yii\util\FileHelper; use yii\base\Application; /** + * View represents a view object in the MVC pattern. + * + * View provides a set of methods (e.g. [[render()]]) for rendering purpose. + * + * * @author Qiang Xue * @since 2.0 */ class View extends Component { /** - * @var Controller|Widget|Object the context under which this view is being rendered + * @var string the layout to be applied when [[render()]] or [[renderContent()]] is called. + * If not set, it will use the value of [[Application::layout]]. */ - public $context; - /** - * @var string|array the directories where the view file should be looked for when a *relative* view name is given. - * This can be either a string representing a single directory, or an array representing multiple directories. - * If the latter, the view file will be looked for in the directories in the order they are specified. - * Path aliases can be used. If this property is not set, relative view names should be treated as absolute ones. - * @see roothPath - */ - public $basePath; + public $layout; /** * @var string the language that the view should be rendered in. If not set, it will use * the value of [[Application::language]]. @@ -45,45 +44,76 @@ class View extends Component * Note that when this is true, if a localized view cannot be found, the original view will be rendered. * No error will be reported. */ - public $localizeView = true; + public $enableI18N = true; /** * @var boolean whether to theme the view when possible. Defaults to true. - * Note that theming will be disabled if [[Application::theme]] is null. + * Note that theming will be disabled if [[Application::theme]] is not set. */ - public $themeView = true; + public $enableTheme = true; /** * @var mixed custom parameters that are available in the view template */ public $params; + + /** + * @var object the object that owns this view. + */ + private $_owner; /** * @var Widget[] the widgets that are currently not ended */ - protected $widgetStack = array(); + private $_widgetStack = array(); /** * Constructor. - * @param Controller|Widget|Object $context the context under which this view is being rendered (e.g. controller, widget) + * @param object $owner the owner of this view. This usually is a controller or a widget. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($context = null, $config = array()) + public function __construct($owner, $config = array()) { - $this->context = $context; + $this->_owner = $owner; parent::__construct($config); } + /** + * Returns the owner of this view. + * @return object the owner of this view. + */ + public function getOwner() + { + return $this->_owner; + } + + /** + * Renders a view within the layout specified by [[owner]]. + * This method is similar to [[renderPartial()]] except that if [[owner]] specifies a layout, + * this method will embed the view result into the layout and then return it. + * @param string $view the view to be rendered. This can be either a path alias or a path relative to [[searchPaths]]. + * @param array $params the parameters that should be made available in the view. The PHP function `extract()` + * will be called on this variable to extract the variables from this parameter. + * @return string the rendering result + * @throws InvalidCallException if the view file cannot be found + * @see renderPartial() + */ public function render($view, $params = array()) { $content = $this->renderPartial($view, $params); - return $this->renderText($content); + return $this->renderContent($content); } - public function renderText($text) + /** + * Renders a text content within the layout specified by [[owner]]. + * If the [[owner]] does not specify any layout, the content will be returned back. + * @param string $content the content to be rendered + * @return string the rendering result + */ + public function renderContent($content) { $layoutFile = $this->findLayoutFile(); if ($layoutFile !== false) { - return $this->renderFile($layoutFile, array('content' => $text)); + return $this->renderFile($layoutFile, array('content' => $content)); } else { - return $text; + return $content; } } @@ -94,18 +124,16 @@ class View extends Component * It then calls [[renderFile()]] to render the view file. The rendering result is returned * as a string. If the view file does not exist, an exception will be thrown. * - * To determine which view file should be rendered, the method calls [[findViewFile()]] which - * will search in the directories as specified by [[basePath]]. - * * View name can be a path alias representing an absolute file path (e.g. `@application/views/layout/index`), - * or a path relative to [[basePath]]. The file suffix is optional and defaults to `.php` if not given + * or a path relative to [[searchPaths]]. The file suffix is optional and defaults to `.php` if not given * in the view name. * - * @param string $view the view to be rendered. This can be either a path alias or a path relative to [[basePath]]. + * @param string $view the view to be rendered. This can be either a path alias or a path relative to [[searchPaths]]. * @param array $params the parameters that should be made available in the view. The PHP function `extract()` * will be called on this variable to extract the variables from this parameter. * @return string the rendering result * @throws InvalidCallException if the view file cannot be found + * @see findViewFile() */ public function renderPartial($view, $params = array()) { @@ -119,19 +147,25 @@ class View extends Component /** * Renders a view file. - * @param string $file the view file path - * @param array $params the parameters to be extracted and made available in the view file + * This method will extract the given parameters and include the view file. + * It captures the output of the included view file and returns it as a string. + * @param string $_file_ the view file. + * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. * @return string the rendering result */ - public function renderFile($file, $params = array()) + public function renderFile($_file_, $_params_ = array()) { - return $this->renderFileInternal($file, $params); + ob_start(); + ob_implicit_flush(false); + extract($_params_, EXTR_OVERWRITE); + require($_file_); + return ob_get_clean(); } public function createWidget($class, $properties = array()) { $properties['class'] = $class; - return \Yii::createObject($properties, $this->context); + return Yii::createObject($properties, $this->_owner); } public function widget($class, $properties = array(), $captureOutput = false) @@ -158,7 +192,7 @@ class View extends Component public function beginWidget($class, $properties = array()) { $widget = $this->createWidget($class, $properties); - $this->widgetStack[] = $widget; + $this->_widgetStack[] = $widget; return $widget; } @@ -173,7 +207,7 @@ class View extends Component public function endWidget() { /** @var $widget Widget */ - if (($widget = array_pop($this->widgetStack)) !== null) { + if (($widget = array_pop($this->_widgetStack)) !== null) { $widget->run(); return $widget; } else { @@ -273,141 +307,75 @@ class View extends Component } /** - * Renders a view file. - * This method will extract the given parameters and include the view file. - * It captures the output of the included view file and returns it as a string. - * @param string $_file_ the view file. - * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. - * @return string the rendering result - */ - protected function renderFileInternal($_file_, $_params_ = array()) - { - ob_start(); - ob_implicit_flush(false); - extract($_params_, EXTR_OVERWRITE); - require($_file_); - return ob_get_clean(); - } - - /** * Finds the view file based on the given view name. + * + * The rule for searching for the view file is as follows: + * + * - If the view name is given as a path alias, return the actual path corresponding to the alias; + * - If the view name does NOT start with a slash: + * * If the view owner is a controller or widget, look for the view file under + * the controller or widget's view path (see [[Controller::viewPath]] and [[Widget::viewPath]]); + * * If the view owner is an object, look for the view file under the "views" sub-directory + * of the directory containing the object class file; + * * Otherwise, look for the view file under the application's [[Application::viewPath|view path]]. + * - If the view name starts with a single slash, look for the view file under the currently active + * module's [[Module::viewPath|view path]]; + * - If the view name starts with double slashes, look for the view file under the application's + * [[Application::viewPath|view path]]. + * + * If [[enableTheme]] is true and there is an active application them, the method will also + * attempt to use a themed version of the view file, when available. + * * @param string $view the view name or path alias. If the view name does not specify * the view file extension name, it will use `.php` as the extension name. - * @return string|boolean the view file if it exists. False if the view file cannot be found. + * @return string|boolean the view file path if it exists. False if the view file cannot be found. */ public function findViewFile($view) { - if (($extension = FileHelper::getExtension($view)) === '') { + if (FileHelper::getExtension($view) === '') { $view .= '.php'; } if (strncmp($view, '@', 1) === 0) { - $file = \Yii::getAlias($view); + // e.g. "@application/views/common" + $file = Yii::getAlias($view); } elseif (strncmp($view, '/', 1) !== 0) { - $file = $this->findRelativeViewFile($view); - } else { - $file = $this->findAbsoluteViewFile($view); - } - - if ($file === false || !is_file($file)) { - return false; - } elseif ($this->localizeView) { - return FileHelper::localize($file, $this->language, $this->sourceLanguage); - } else { - return $file; - } - } - - /** - * Finds the view file corresponding to the given relative view name. - * The method will look for the view file under a set of directories returned by [[resolveBasePath()]]. - * If no base path is given, the view will be treated as an absolute view and the result of - * [[findAbsoluteViewFile()]] will be returned. - * @param string $view the relative view name - * @return string|boolean the view file path, or false if the view file cannot be found - */ - protected function findRelativeViewFile($view) - { - $paths = $this->resolveBasePath(); - if ($paths === array()) { - return $this->findAbsoluteViewFile($view); - } - if ($this->themeView && $this->context !== null && ($theme = \Yii::$application->getTheme()) !== null) { - array_unshift($paths, $theme->getViewPath($this->context)); - } - foreach ($paths as $path) { - $file = \Yii::getAlias($path . '/' . $view); - if ($file !== false && is_file($file)) { - return $file; + // e.g. "index" + if ($this->_owner instanceof Controller || $this->_owner instanceof Widget) { + $path = $this->_owner->getViewPath() . DIRECTORY_SEPARATOR . $view; + } elseif ($this->_owner !== null) { + $class = new \ReflectionClass($this->_owner); + $path = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views'; + } else { + $path = Yii::$application->getViewPath(); } - } - return $paths === array() ? $this->findAbsoluteViewFile($view) : false; - } - - /** - * Finds the view file corresponding to the given absolute view name. - * If the view name starts with double slashes `//`, the method will look for the view file - * under [[Application::getViewPath()]]. Otherwise, it will look for the view file under the - * view path of the currently active module. - * @param string $view the absolute view name - * @return string|boolean the view file path, or false if the view file cannot be found - */ - protected function findAbsoluteViewFile($view) - { - $app = \Yii::$application; - if (strncmp($view, '//', 2) !== 0 && $app->controller !== null) { - $module = $app->controller->module; + $file = $path . DIRECTORY_SEPARATOR . $view; + } elseif (strncmp($view, '//', 2) !== 0 && Yii::$application->controller !== null) { + // e.g. "/site/index" + $file = Yii::$application->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); } else { - $module = $app; + // e.g. "//layouts/main" + $file = Yii::$application->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); } - if ($this->themeView && ($theme = $app->getTheme()) !== null) { - $paths[] = $theme->getViewPath($module); - } - $paths[] = $module->getViewPath(); - $view = ltrim($view, '/'); - foreach ($paths as $path) { - $file = \Yii::getAlias($path . '/' . $view); - if ($file !== false && is_file($file)) { - return $file; - } - } - return false; - } - /** - * Resolves the base paths that will be used to determine view files for relative view names. - * The method resolves the base path using the following algorithm: - * - * - If [[basePath]] is not empty, it is returned; - * - If [[context]] is a controller, it will return the subdirectory named as - * [[Controller::uniqueId]] under the controller's module view path; - * - If [[context]] is an object, it will return the `views` subdirectory under - * the directory containing the object class file. - * - Otherwise, it will return false. - * @return array the base paths - */ - protected function resolveBasePath() - { - if (!empty($this->basePath)) { - return (array)$this->basePath; - } elseif ($this->context instanceof Controller) { - return array($this->context->module->getViewPath() . '/' . $this->context->getUniqueId()); - } elseif ($this->context !== null) { - $class = new \ReflectionClass($this->context); - return array(dirname($class->getFileName()) . '/views'); + if (is_file($file)) { + if ($this->enableTheme && ($theme = Yii::$application->getTheme()) !== null) { + $file = $theme->apply($file); + } + return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file; } else { - return array(); + return false; } } /** - * Finds the layout file for the current [[context]]. - * The method will return false if [[context]] is not a controller. - * When [[context]] is a controller, the following algorithm is used to determine the layout file: + * Finds the layout file for the current [[owner]]. + * The method will return false if [[owner]] is not a controller. + * When [[owner]] is a controller, the following algorithm is used to determine the layout file: * - * - If `context.layout` is false, it will return false; - * - If `context.layout` is a string, it will look for the layout file under the [[Module::layoutPath|layout path]] + * - If `content` is not a controller or if `owner.layout` is false, it will return false; + * - If `owner.layout` is a string, it will look for the layout file under the [[Module::layoutPath|layout path]] * of the controller's parent module; - * - If `context.layout` is null, the following steps are taken to resolve the actual layout to be returned: + * - If `owner.layout` is null, the following steps are taken to resolve the actual layout to be returned: * * Check the `layout` property of the parent module. If it is null, check the grand parent module and so on * until a non-null layout is encountered. Let's call this module the *effective module*. * * If the layout is null or false, it will return false; @@ -415,15 +383,21 @@ class View extends Component * * The themed layout file will be returned if theme is enabled and the theme contains such a layout file. * - * @return string|boolean the layout file path, or false if the context does not need layout. + * @return string|boolean the layout file path, or false if the owner does not need layout. * @throws InvalidCallException if the layout file cannot be found */ public function findLayoutFile() { - if (!$this->context instanceof Controller || $this->context->layout === false) { + if ($this->layout === null || !$this->_owner instanceof Controller) { + $layout = Yii::$application->layout; + } elseif ($this->_owner->layout !== false) { + + } + if (!$this->_owner instanceof Controller || $this->_owner->layout === false) { return false; } - $module = $this->context->module; + /** @var $module Module */ + $module = $this->_owner->module; while ($module !== null && $module->layout === null) { $module = $module->module; } @@ -432,21 +406,35 @@ class View extends Component } $view = $module->layout; - if (($extension = FileHelper::getExtension($view)) === '') { + if (FileHelper::getExtension($view) === '') { $view .= '.php'; } if (strncmp($view, '@', 1) === 0) { - $file = \Yii::getAlias($view); + $file = Yii::getAlias($view); + } elseif (strncmp($view, '/', 1) !== 0) { + // e.g. "main" + if ($this->_owner instanceof Controller || $this->_owner instanceof Widget) { + $path = $this->_owner->getViewPath() . DIRECTORY_SEPARATOR . $view; + } elseif ($this->_owner !== null) { + $class = new \ReflectionClass($this->_owner); + $path = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views'; + } else { + $path = Yii::$application->getViewPath(); + } + $file = $path . DIRECTORY_SEPARATOR . $view; + } elseif (strncmp($view, '//', 2) !== 0 && Yii::$application->controller !== null) { + // e.g. "/main" + $file = Yii::$application->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); + } else { + // e.g. "//main" + $file = Yii::$application->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); } elseif (strncmp($view, '/', 1) === 0) { $file = $this->findAbsoluteViewFile($view); } else { - if ($this->themeView && ($theme = \Yii::$application->getTheme()) !== null) { - $paths[] = $theme->getLayoutPath($module); - } $paths[] = $module->getLayoutPath(); $file = false; foreach ($paths as $path) { - $f = \Yii::getAlias($path . '/' . $view); + $f = Yii::getAlias($path . '/' . $view); if ($f !== false && is_file($f)) { $file = $f; break; @@ -455,7 +443,7 @@ class View extends Component } if ($file === false || !is_file($file)) { throw new InvalidCallException("Unable to find the layout file for layout '{$module->layout}' (specified by " . get_class($module) . ")"); - } elseif ($this->localizeView) { + } elseif ($this->enableI18N) { return FileHelper::localize($file, $this->language, $this->sourceLanguage); } else { return $file; diff --git a/framework/base/Widget.php b/framework/base/Widget.php index 686e58e..ba5eb82 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -102,4 +102,16 @@ class Widget extends Component { return new View($this); } + + /** + * Returns the directory containing the view files for this widget. + * The default implementation returns the 'views' subdirectory under the directory containing the widget class file. + * @return string the directory containing the view files for this widget. + */ + public function getViewPath() + { + $className = get_class($this); + $class = new \ReflectionClass($className); + return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views'; + } } \ No newline at end of file diff --git a/framework/util/FileHelper.php b/framework/util/FileHelper.php index d340338..c65e4f0 100644 --- a/framework/util/FileHelper.php +++ b/framework/util/FileHelper.php @@ -51,6 +51,20 @@ class FileHelper } /** + * Normalizes a file/directory path. + * After normalization, the directory separators in the path will be `DIRECTORY_SEPARATOR`, + * and any trailing directory separators will be removed. For example, '/home\demo/' on Linux + * will be normalized as '/home/demo'. + * @param string $path the file/directory path to be normalized + * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`. + * @return string the normalized file/directory path + */ + public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR) + { + return rtrim(strtr($path, array('/' => $ds, '\\' => $ds)), $ds); + } + + /** * Returns the localized version of a specified file. * * The searching is based on the specified language code. In particular, From 311f876b7bc270ab198b85db4b418dfb842d7927 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Wed, 30 Jan 2013 23:34:04 -0500 Subject: [PATCH 08/14] MVC WIP --- framework/base/Controller.php | 4 +- framework/base/ErrorHandler.php | 2 +- framework/base/View.php | 432 +++++++++++++++++++++------------------- framework/base/Widget.php | 2 +- 4 files changed, 229 insertions(+), 211 deletions(-) diff --git a/framework/base/Controller.php b/framework/base/Controller.php index d8cfbd2..9be3d6e 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -265,9 +265,9 @@ class Controller extends Component return $this->createView()->render($view, $params); } - public function renderText($text) + public function renderContent($content) { - return $this->createView()->renderText($text); + return $this->createView()->renderContent($content); } public function renderPartial($view, $params = array()) diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index 23b5d57..a095509 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -321,7 +321,7 @@ class ErrorHandler extends Component public function renderAsHtml($exception) { $view = new View; - $view->_owner = $this; + $view->owner = $this; $name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView; echo $view->render($name, array( 'exception' => $exception, diff --git a/framework/base/View.php b/framework/base/View.php index f4dd07b..d152d39 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -18,15 +18,18 @@ use yii\base\Application; * * View provides a set of methods (e.g. [[render()]]) for rendering purpose. * - * * @author Qiang Xue * @since 2.0 */ class View extends Component { /** - * @var string the layout to be applied when [[render()]] or [[renderContent()]] is called. - * If not set, it will use the value of [[Application::layout]]. + * @var object the object that owns this view. This can be a controller, a widget, or any other object. + */ + public $owner; + /** + * @var string|boolean the layout to be applied when [[render()]] or [[renderContent()]] is called. + * If not set, it will use the value of [[Application::layout]]. If false, no layout will be applied. */ public $layout; /** @@ -56,10 +59,6 @@ class View extends Component public $params; /** - * @var object the object that owns this view. - */ - private $_owner; - /** * @var Widget[] the widgets that are currently not ended */ private $_widgetStack = array(); @@ -71,29 +70,21 @@ class View extends Component */ public function __construct($owner, $config = array()) { - $this->_owner = $owner; + $this->owner = $owner; parent::__construct($config); } /** - * Returns the owner of this view. - * @return object the owner of this view. - */ - public function getOwner() - { - return $this->_owner; - } - - /** - * Renders a view within the layout specified by [[owner]]. - * This method is similar to [[renderPartial()]] except that if [[owner]] specifies a layout, + * Renders a view within a layout. + * This method is similar to [[renderPartial()]] except that if a layout is available, * this method will embed the view result into the layout and then return it. - * @param string $view the view to be rendered. This can be either a path alias or a path relative to [[searchPaths]]. + * @param string $view the view to be rendered. Please refer to [[findViewFile()]] on possible formats of the view name. * @param array $params the parameters that should be made available in the view. The PHP function `extract()` * will be called on this variable to extract the variables from this parameter. * @return string the rendering result - * @throws InvalidCallException if the view file cannot be found - * @see renderPartial() + * @throws InvalidConfigException if the view file or layout file cannot be found + * @see findViewFile() + * @see findLayoutFile() */ public function render($view, $params = array()) { @@ -102,10 +93,13 @@ class View extends Component } /** - * Renders a text content within the layout specified by [[owner]]. - * If the [[owner]] does not specify any layout, the content will be returned back. + * Renders a text content within a layout. + * The layout being used is resolved by [[findLayout()]]. + * If no layout is available, the content will be returned back. * @param string $content the content to be rendered * @return string the rendering result + * @throws InvalidConfigException if the layout file cannot be found + * @see findLayoutFile() */ public function renderContent($content) { @@ -124,11 +118,7 @@ class View extends Component * It then calls [[renderFile()]] to render the view file. The rendering result is returned * as a string. If the view file does not exist, an exception will be thrown. * - * View name can be a path alias representing an absolute file path (e.g. `@application/views/layout/index`), - * or a path relative to [[searchPaths]]. The file suffix is optional and defaults to `.php` if not given - * in the view name. - * - * @param string $view the view to be rendered. This can be either a path alias or a path relative to [[searchPaths]]. + * @param string $view the view to be rendered. Please refer to [[findViewFile()]] on possible formats of the view name. * @param array $params the parameters that should be made available in the view. The PHP function `extract()` * will be called on this variable to extract the variables from this parameter. * @return string the rendering result @@ -162,12 +152,29 @@ class View extends Component return ob_get_clean(); } + /** + * Creates a widget. + * This method will use [[Yii::createObject()]] to create the widget. + * @param string $class the widget class name or path alias + * @param array $properties the initial property values of the widget. + * @return Widget the newly created widget instance + */ public function createWidget($class, $properties = array()) { $properties['class'] = $class; - return Yii::createObject($properties, $this->_owner); + return Yii::createObject($properties, $this->owner); } + /** + * Creates and runs a widget. + * Compared with [[createWidget()]], this method does one more thing: it will + * run the widget after it is created. + * @param string $class the widget class name or path alias + * @param array $properties the initial property values of the widget. + * @param boolean $captureOutput whether to capture the output of the widget and return it as a string + * @return string|Widget if $captureOutput is true, the output of the widget will be returned; + * otherwise the widget object will be returned. + */ public function widget($class, $properties = array(), $captureOutput = false) { if ($captureOutput) { @@ -185,8 +192,10 @@ class View extends Component /** * Begins a widget. - * @param string $class the widget class - * @param array $properties the initial property values of the widget + * This method is similar to [[createWidget()]] except that it will expect a matching + * [[endWidget()]] call after this. + * @param string $class the widget class name or path alias + * @param array $properties the initial property values of the widget. * @return Widget the widget instance */ public function beginWidget($class, $properties = array()) @@ -206,129 +215,134 @@ class View extends Component */ public function endWidget() { - /** @var $widget Widget */ - if (($widget = array_pop($this->_widgetStack)) !== null) { + $widget = array_pop($this->_widgetStack); + if ($widget instanceof Widget) { $widget->run(); return $widget; } else { throw new Exception("Unmatched beginWidget() and endWidget() calls."); } } - - /** - * Begins recording a clip. - * This method is a shortcut to beginning [[yii\widgets\Clip]] - * @param string $id the clip ID. - * @param array $properties initial property values for [[yii\widgets\Clip]] - */ - public function beginClip($id, $properties = array()) - { - $properties['id'] = $id; - $this->beginWidget('yii\widgets\Clip', $properties); - } - - /** - * Ends recording a clip. - */ - public function endClip() - { - $this->endWidget(); - } - - /** - * Begins fragment caching. - * This method will display cached content if it is available. - * If not, it will start caching and would expect an [[endCache()]] - * call to end the cache and save the content into cache. - * A typical usage of fragment caching is as follows, - * - * ~~~ - * if($this->beginCache($id)) { - * // ...generate content here - * $this->endCache(); - * } - * ~~~ - * - * @param string $id a unique ID identifying the fragment to be cached. - * @param array $properties initial property values for [[yii\widgets\OutputCache]] - * @return boolean whether we need to generate content for caching. False if cached version is available. - * @see endCache - */ - public function beginCache($id, $properties = array()) - { - $properties['id'] = $id; - $cache = $this->beginWidget('yii\widgets\OutputCache', $properties); - if ($cache->getIsContentCached()) { - $this->endCache(); - return false; - } else { - return true; - } - } - - /** - * Ends fragment caching. - * This is an alias to [[endWidget()]] - * @see beginCache - */ - public function endCache() - { - $this->endWidget(); - } - - /** - * Begins the rendering of content that is to be decorated by the specified view. - * @param mixed $view the name of the view that will be used to decorate the content. The actual view script - * is resolved via {@link getViewFile}. If this parameter is null (default), - * the default layout will be used as the decorative view. - * Note that if the current controller does not belong to - * any module, the default layout refers to the application's {@link CWebApplication::layout default layout}; - * If the controller belongs to a module, the default layout refers to the module's - * {@link CWebModule::layout default layout}. - * @param array $params the variables (name=>value) to be extracted and made available in the decorative view. - * @see endContent - * @see yii\widgets\ContentDecorator - */ - public function beginContent($view, $params = array()) - { - $this->beginWidget('yii\widgets\ContentDecorator', array( - 'view' => $view, - 'params' => $params, - )); - } - - /** - * Ends the rendering of content. - * @see beginContent - */ - public function endContent() - { - $this->endWidget(); - } +// +// /** +// * Begins recording a clip. +// * This method is a shortcut to beginning [[yii\widgets\Clip]] +// * @param string $id the clip ID. +// * @param array $properties initial property values for [[yii\widgets\Clip]] +// */ +// public function beginClip($id, $properties = array()) +// { +// $properties['id'] = $id; +// $this->beginWidget('yii\widgets\Clip', $properties); +// } +// +// /** +// * Ends recording a clip. +// */ +// public function endClip() +// { +// $this->endWidget(); +// } +// +// /** +// * Begins fragment caching. +// * This method will display cached content if it is available. +// * If not, it will start caching and would expect an [[endCache()]] +// * call to end the cache and save the content into cache. +// * A typical usage of fragment caching is as follows, +// * +// * ~~~ +// * if($this->beginCache($id)) { +// * // ...generate content here +// * $this->endCache(); +// * } +// * ~~~ +// * +// * @param string $id a unique ID identifying the fragment to be cached. +// * @param array $properties initial property values for [[yii\widgets\OutputCache]] +// * @return boolean whether we need to generate content for caching. False if cached version is available. +// * @see endCache +// */ +// public function beginCache($id, $properties = array()) +// { +// $properties['id'] = $id; +// $cache = $this->beginWidget('yii\widgets\OutputCache', $properties); +// if ($cache->getIsContentCached()) { +// $this->endCache(); +// return false; +// } else { +// return true; +// } +// } +// +// /** +// * Ends fragment caching. +// * This is an alias to [[endWidget()]] +// * @see beginCache +// */ +// public function endCache() +// { +// $this->endWidget(); +// } +// +// /** +// * Begins the rendering of content that is to be decorated by the specified view. +// * @param mixed $view the name of the view that will be used to decorate the content. The actual view script +// * is resolved via {@link getViewFile}. If this parameter is null (default), +// * the default layout will be used as the decorative view. +// * Note that if the current controller does not belong to +// * any module, the default layout refers to the application's {@link CWebApplication::layout default layout}; +// * If the controller belongs to a module, the default layout refers to the module's +// * {@link CWebModule::layout default layout}. +// * @param array $params the variables (name=>value) to be extracted and made available in the decorative view. +// * @see endContent +// * @see yii\widgets\ContentDecorator +// */ +// public function beginContent($view, $params = array()) +// { +// $this->beginWidget('yii\widgets\ContentDecorator', array( +// 'view' => $view, +// 'params' => $params, +// )); +// } +// +// /** +// * Ends the rendering of content. +// * @see beginContent +// */ +// public function endContent() +// { +// $this->endWidget(); +// } /** * Finds the view file based on the given view name. * - * The rule for searching for the view file is as follows: + * A view name can be specified in one of the following formats: + * + * - path alias (e.g. "@application/views/site/index"); + * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. + * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application. + * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash. + * The actual view file will be looked for under the [[Module::viewPath|view path]] of the currently + * active module. + * - relative path (e.g. "index"): the actual view file will be looked for under the [[owner]]'s view path. + * If [[owner]] is a widget or a controller, its view path is given by their `viewPath` property. + * If [[owner]] is an object of any other type, its view path is the `view` sub-directory of the directory + * containing the owner class file. * - * - If the view name is given as a path alias, return the actual path corresponding to the alias; - * - If the view name does NOT start with a slash: - * * If the view owner is a controller or widget, look for the view file under - * the controller or widget's view path (see [[Controller::viewPath]] and [[Widget::viewPath]]); - * * If the view owner is an object, look for the view file under the "views" sub-directory - * of the directory containing the object class file; - * * Otherwise, look for the view file under the application's [[Application::viewPath|view path]]. - * - If the view name starts with a single slash, look for the view file under the currently active - * module's [[Module::viewPath|view path]]; - * - If the view name starts with double slashes, look for the view file under the application's - * [[Application::viewPath|view path]]. + * If the view name does not contain a file extension, it will default to `.php`. * * If [[enableTheme]] is true and there is an active application them, the method will also * attempt to use a themed version of the view file, when available. * + * And if [[enableI18N]] is true, the method will attempt to use a translated version of the view file, + * when available. + * * @param string $view the view name or path alias. If the view name does not specify * the view file extension name, it will use `.php` as the extension name. - * @return string|boolean the view file path if it exists. False if the view file cannot be found. + * @return string the view file path if it exists. False if the view file cannot be found. + * @throws InvalidConfigException if the view file does not exist */ public function findViewFile($view) { @@ -337,18 +351,19 @@ class View extends Component } if (strncmp($view, '@', 1) === 0) { // e.g. "@application/views/common" - $file = Yii::getAlias($view); + if (($file = Yii::getAlias($view)) === false) { + throw new InvalidConfigException("Invalid path alias: $view"); + } } elseif (strncmp($view, '/', 1) !== 0) { // e.g. "index" - if ($this->_owner instanceof Controller || $this->_owner instanceof Widget) { - $path = $this->_owner->getViewPath() . DIRECTORY_SEPARATOR . $view; - } elseif ($this->_owner !== null) { - $class = new \ReflectionClass($this->_owner); - $path = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views'; + if ($this->owner instanceof Controller || $this->owner instanceof Widget) { + $file = $this->owner->getViewPath() . DIRECTORY_SEPARATOR . $view; + } elseif ($this->owner !== null) { + $class = new \ReflectionClass($this->owner); + $file = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view; } else { - $path = Yii::$application->getViewPath(); + $file = Yii::$application->getViewPath() . DIRECTORY_SEPARATOR . $view; } - $file = $path . DIRECTORY_SEPARATOR . $view; } elseif (strncmp($view, '//', 2) !== 0 && Yii::$application->controller !== null) { // e.g. "/site/index" $file = Yii::$application->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); @@ -363,90 +378,93 @@ class View extends Component } return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file; } else { - return false; + throw new InvalidConfigException("View file for view '$view' does not exist: $file"); } } /** - * Finds the layout file for the current [[owner]]. - * The method will return false if [[owner]] is not a controller. - * When [[owner]] is a controller, the following algorithm is used to determine the layout file: + * Finds the layout file that can be applied to the view. * - * - If `content` is not a controller or if `owner.layout` is false, it will return false; - * - If `owner.layout` is a string, it will look for the layout file under the [[Module::layoutPath|layout path]] - * of the controller's parent module; - * - If `owner.layout` is null, the following steps are taken to resolve the actual layout to be returned: - * * Check the `layout` property of the parent module. If it is null, check the grand parent module and so on - * until a non-null layout is encountered. Let's call this module the *effective module*. - * * If the layout is null or false, it will return false; - * * Otherwise, it will look for the layout file under the layout path of the effective module. + * The applicable layout is resolved according to the following rules: * - * The themed layout file will be returned if theme is enabled and the theme contains such a layout file. + * - If [[layout]] is specified as a string, use it as the layout name and search for the layout file + * under the layout path of the currently active module; + * - If [[layout]] is null and [[owner]] is a controller: + * * If the controller's [[Controller::layout|layout]] is a string, use it as the layout name + * and search for the layout file under the layout path of the parent module of the controller; + * * If the controller's [[Controller::layout|layout]] is null, look through its ancestor modules + * and find one whose [[Module::layout|layout]] is not null. Use the layout specified by that module; + * - Returns false for all other cases. * - * @return string|boolean the layout file path, or false if the owner does not need layout. - * @throws InvalidCallException if the layout file cannot be found + * Like view names, a layout name can take several formats: + * + * - path alias (e.g. "@application/views/layouts/main"); + * - absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be + * looked for under the [[Application::layoutPath|layout path]] of the application; + * - relative path (e.g. "main"): the actual layout layout file will be looked for under the + * [[Module::viewPath|view path]] of the context module determined by the above layout resolution process. + * + * If the layout name does not contain a file extension, it will default to `.php`. + * + * If [[enableTheme]] is true and there is an active application them, the method will also + * attempt to use a themed version of the layout file, when available. + * + * And if [[enableI18N]] is true, the method will attempt to use a translated version of the layout file, + * when available. + * + * @return string|boolean the layout file path, or false if layout is not needed. + * @throws InvalidConfigException if the layout file cannot be found */ public function findLayoutFile() { - if ($this->layout === null || !$this->_owner instanceof Controller) { - $layout = Yii::$application->layout; - } elseif ($this->_owner->layout !== false) { - - } - if (!$this->_owner instanceof Controller || $this->_owner->layout === false) { - return false; - } /** @var $module Module */ - $module = $this->_owner->module; - while ($module !== null && $module->layout === null) { - $module = $module->module; - } - if ($module === null || $module->layout === null || $module->layout === false) { + if (is_string($this->layout)) { + if (Yii::$application->controller) { + $module = Yii::$application->controller->module; + } else { + $module = Yii::$application; + } + $view = $this->layout; + } elseif ($this->layout === null && $this->owner instanceof Controller) { + if (is_string($this->owner->layout)) { + $module = $this->owner->module; + $view = $this->owner->layout; + } elseif ($this->owner->layout === null) { + $module = $this->owner->module; + while ($module !== null && $module->layout === null) { + $module = $module->module; + } + if ($module === null || !is_string($module->layout)) { + return false; + } + $view = $module->layout; + } else { + return false; + } + } else { return false; } - $view = $module->layout; if (FileHelper::getExtension($view) === '') { $view .= '.php'; } if (strncmp($view, '@', 1) === 0) { - $file = Yii::getAlias($view); - } elseif (strncmp($view, '/', 1) !== 0) { - // e.g. "main" - if ($this->_owner instanceof Controller || $this->_owner instanceof Widget) { - $path = $this->_owner->getViewPath() . DIRECTORY_SEPARATOR . $view; - } elseif ($this->_owner !== null) { - $class = new \ReflectionClass($this->_owner); - $path = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views'; - } else { - $path = Yii::$application->getViewPath(); + if (($file = Yii::getAlias($view)) === false) { + throw new InvalidConfigException("Invalid path alias: $view"); } - $file = $path . DIRECTORY_SEPARATOR . $view; - } elseif (strncmp($view, '//', 2) !== 0 && Yii::$application->controller !== null) { - // e.g. "/main" - $file = Yii::$application->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); - } else { - // e.g. "//main" - $file = Yii::$application->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); } elseif (strncmp($view, '/', 1) === 0) { - $file = $this->findAbsoluteViewFile($view); + $file = Yii::$application->getLayoutPath() . DIRECTORY_SEPARATOR . $view; } else { - $paths[] = $module->getLayoutPath(); - $file = false; - foreach ($paths as $path) { - $f = Yii::getAlias($path . '/' . $view); - if ($f !== false && is_file($f)) { - $file = $f; - break; - } - } + $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $view; } - if ($file === false || !is_file($file)) { - throw new InvalidCallException("Unable to find the layout file for layout '{$module->layout}' (specified by " . get_class($module) . ")"); - } elseif ($this->enableI18N) { - return FileHelper::localize($file, $this->language, $this->sourceLanguage); + + if (is_file($file)) { + if ($this->enableTheme && ($theme = Yii::$application->getTheme()) !== null) { + $file = $theme->apply($file); + } + return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file; } else { - return $file; + throw new InvalidConfigException("Layout file for layout '$view' does not exist: $file"); } } } \ No newline at end of file diff --git a/framework/base/Widget.php b/framework/base/Widget.php index ba5eb82..bdec634 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -49,7 +49,7 @@ class Widget extends Component public function getId($autoGenerate = true) { if ($autoGenerate && $this->_id === null) { - $this->_id = 'yw' . self::$_counter++; + $this->_id = 'w' . self::$_counter++; } return $this->_id; } From 4402073d97ace2334d484e9be4993ab5df15ed19 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 31 Jan 2013 08:51:30 -0500 Subject: [PATCH 09/14] MVC WIP --- framework/base/View.php | 20 ++++++++--------- framework/console/Controller.php | 46 ++++++++++++++++------------------------ 2 files changed, 28 insertions(+), 38 deletions(-) diff --git a/framework/base/View.php b/framework/base/View.php index d152d39..dccfb26 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -28,8 +28,8 @@ class View extends Component */ public $owner; /** - * @var string|boolean the layout to be applied when [[render()]] or [[renderContent()]] is called. - * If not set, it will use the value of [[Application::layout]]. If false, no layout will be applied. + * @var string the layout to be applied when [[render()]] or [[renderContent()]] is called. + * If not set, it will use the [[Module::layout]] of the currently active module. */ public $layout; /** @@ -393,7 +393,8 @@ class View extends Component * * If the controller's [[Controller::layout|layout]] is a string, use it as the layout name * and search for the layout file under the layout path of the parent module of the controller; * * If the controller's [[Controller::layout|layout]] is null, look through its ancestor modules - * and find one whose [[Module::layout|layout]] is not null. Use the layout specified by that module; + * and find the first one whose [[Module::layout|layout]] is not null. Use the layout specified + * by that module; * - Returns false for all other cases. * * Like view names, a layout name can take several formats: @@ -425,7 +426,7 @@ class View extends Component $module = Yii::$application; } $view = $this->layout; - } elseif ($this->layout === null && $this->owner instanceof Controller) { + } elseif ($this->owner instanceof Controller) { if (is_string($this->owner->layout)) { $module = $this->owner->module; $view = $this->owner->layout; @@ -434,14 +435,13 @@ class View extends Component while ($module !== null && $module->layout === null) { $module = $module->module; } - if ($module === null || !is_string($module->layout)) { - return false; + if ($module !== null && is_string($module->layout)) { + $view = $module->layout; } - $view = $module->layout; - } else { - return false; } - } else { + } + + if (!isset($view)) { return false; } diff --git a/framework/console/Controller.php b/framework/console/Controller.php index 164f631..f7155b0 100644 --- a/framework/console/Controller.php +++ b/framework/console/Controller.php @@ -9,9 +9,10 @@ namespace yii\console; +use Yii; use yii\base\Action; +use yii\base\InvalidRequestException; use yii\base\InvalidRouteException; -use yii\base\Exception; /** * Controller is the base class of console command classes. @@ -57,35 +58,24 @@ class Controller extends \yii\base\Controller } /** - * This method is invoked when the request parameters do not satisfy the requirement of the specified action. - * The default implementation will throw an exception. - * @param Action $action the action being executed - * @param Exception $exception the exception about the invalid parameters + * Validates the parameter being bound to actions. + * This method is invoked when parameters are being bound to the currently requested action. + * Child classes may override this method to throw exceptions when there are missing and/or unknown parameters. + * @param Action $action the currently requested action + * @param array $missingParams the names of the missing parameters + * @param array $unknownParams the unknown parameters (name=>value) + * @throws InvalidRequestException if there are missing or unknown parameters */ - public function invalidActionParams($action, $exception) + public function validateActionParams($action, $missingParams, $unknownParams) { - echo \Yii::t('yii', 'Error: {message}', array( - '{message}' => $exception->getMessage(), - )); - \Yii::$application->end(1); - } - - /** - * This method is invoked when extra parameters are provided to an action while it is executed. - * @param Action $action the action being executed - * @param array $expected the expected action parameters (name => value) - * @param array $actual the actual action parameters (name => value) - */ - public function extraActionParams($action, $expected, $actual) - { - unset($expected['args'], $actual['args']); - - $keys = array_diff(array_keys($actual), array_keys($expected)); - if (!empty($keys)) { - echo \Yii::t('yii', 'Error: Unknown parameter(s): {params}', array( - '{params}' => implode(', ', $keys), - )) . "\n"; - \Yii::$application->end(1); + if (!empty($missingParams)) { + throw new InvalidRequestException(Yii::t('yii', 'Missing required options: {params}', array( + '{params}' => implode(', ', $missingParams), + ))); + } elseif (!empty($unknownParams)) { + throw new InvalidRequestException(Yii::t('yii', 'Unknown options: {params}', array( + '{params}' => implode(', ', $unknownParams), + ))); } } From e09a791c921e2b0f2a11db9941e06c335190d10a Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 31 Jan 2013 15:05:49 -0500 Subject: [PATCH 10/14] MVC cleanup --- framework/base/Controller.php | 10 ++-- framework/base/ErrorHandler.php | 3 +- framework/base/InlineAction.php | 2 +- framework/base/Module.php | 62 +++++++++++----------- framework/console/Application.php | 26 ++++++++- framework/console/controllers/CreateController.php | 4 +- framework/console/controllers/HelpController.php | 31 +++++------ framework/util/ConsoleHelper.php | 2 +- framework/yiic.php | 10 ++-- 9 files changed, 84 insertions(+), 66 deletions(-) diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 9be3d6e..804b339 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -100,10 +100,6 @@ class Controller extends Component */ public function runAction($id, $params = array()) { - if ($id === '') { - $id = $this->defaultAction; - } - $action = $this->createAction($id); if ($action !== null) { $oldAction = $this->action; @@ -143,7 +139,7 @@ class Controller extends Component } elseif ($pos > 0) { return $this->module->runAction($route, $params); } else { - return \Yii::$application->runAction($route, $params); + return \Yii::$application->runAction(ltrim($route, '/'), $params); } } @@ -174,6 +170,10 @@ class Controller extends Component */ public function createAction($id) { + if ($id === '') { + $id = $this->defaultAction; + } + $actionMap = $this->actions(); if (isset($actionMap[$id])) { return Yii::createObject($actionMap[$id], $id, $this); diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index a095509..5b48fbf 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -320,8 +320,7 @@ class ErrorHandler extends Component */ public function renderAsHtml($exception) { - $view = new View; - $view->owner = $this; + $view = new View($this); $name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView; echo $view->render($name, array( 'exception' => $exception, diff --git a/framework/base/InlineAction.php b/framework/base/InlineAction.php index 00ecb8f..4cd5413 100644 --- a/framework/base/InlineAction.php +++ b/framework/base/InlineAction.php @@ -47,6 +47,6 @@ class InlineAction extends Action { $method = new \ReflectionMethod($this->controller, $this->actionMethod); $args = $this->bindActionParams($method, $params); - return (int)$method->invokeArgs($this, $args); + return (int)$method->invokeArgs($this->controller, $args); } } diff --git a/framework/base/Module.php b/framework/base/Module.php index 966cc64..dcb468c 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -559,53 +559,52 @@ abstract class Module extends Component */ public function runAction($route, $params = array()) { - $route = trim($route, '/'); - if ($route === '') { - $route = trim($this->defaultRoute, '/'); - } - if (($pos = strpos($route, '/')) !== false) { - $id = substr($route, 0, $pos); - $route2 = substr($route, $pos + 1); - } else { - $id = $route; - $route2 = ''; - } - - $module = $this->getModule($id); - if ($module !== null) { - return $module->runAction($route2, $params); - } - - $controller = $this->createController($id); - if ($controller !== null) { + $result = $this->createController($route); + if (is_array($result)) { + /** @var $controller Controller */ + list($controller, $actionID) = $result; $oldController = Yii::$application->controller; Yii::$application->controller = $controller; - - $status = $controller->runAction($route2, $params); - + $status = $controller->runAction($actionID, $params); Yii::$application->controller = $oldController; - return $status; } else { - throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $route); + throw new InvalidRouteException('Unable to resolve the request: ' . trim($this->getUniqueId() . '/' . $route, '/')); } } /** * Creates a controller instance based on the controller ID. * - * The controller is created within the given module. The method first attempts to + * The controller is created within this module. The method first attempts to * create the controller based on the [[controllerMap]] of the module. If not available, * it will look for the controller class under the [[controllerPath]] and create an * instance of it. * - * @param string $id the controller ID - * @return Controller the newly created controller instance + * @param string $route the route consisting of module, controller and action IDs. + * @return array|boolean if the controller is created successfully, it will be returned together + * with the remainder of the route which represents the action ID. Otherwise false will be returned. */ - public function createController($id) + public function createController($route) { + if ($route === '') { + $route = $this->defaultRoute; + } + if (($pos = strpos($route, '/')) !== false) { + $id = substr($route, 0, $pos); + $route = substr($route, $pos + 1); + } else { + $id = $route; + $route = ''; + } + + $module = $this->getModule($id); + if ($module !== null) { + return $module->createController($route); + } + if (isset($this->controllerMap[$id])) { - return Yii::createObject($this->controllerMap[$id], $id, $this); + $controller = Yii::createObject($this->controllerMap[$id], $id, $this); } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) { $className = StringHelper::id2camel($id) . 'Controller'; $classFile = $this->controllerPath . DIRECTORY_SEPARATOR . $className . '.php'; @@ -615,10 +614,11 @@ abstract class Module extends Component require($classFile); } if (class_exists($className, false) && is_subclass_of($className, '\yii\base\Controller')) { - return new $className($id, $this); + $controller = new $className($id, $this); } } } - return null; + + return isset($controller) ? array($controller, $route) : false; } } diff --git a/framework/console/Application.php b/framework/console/Application.php index 1b3192e..6ad40cc 100644 --- a/framework/console/Application.php +++ b/framework/console/Application.php @@ -10,7 +10,7 @@ namespace yii\console; use yii\base\Exception; -use yii\util\ReflectionHelper; +use yii\base\InvalidRouteException; /** * Application represents a console application. @@ -94,7 +94,29 @@ class Application extends \yii\base\Application if ($request->getIsConsoleRequest()) { return $this->runAction($request->route, $request->params); } else { - die('This script must be run from the command line.'); + echo "Error: this script must be run from the command line."; + return 1; + } + } + + + /** + * Runs a controller action specified by a route. + * This method parses the specified route and creates the corresponding child module(s), controller and action + * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters. + * If the route is empty, the method will use [[defaultRoute]]. + * @param string $route the route that specifies 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. + * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully + */ + public function runAction($route, $params = array()) + { + try { + return parent::runAction($route, $params); + } catch (InvalidRouteException $e) { + echo "\nError: unknown command \"$route\".\n"; + return 1; } } diff --git a/framework/console/controllers/CreateController.php b/framework/console/controllers/CreateController.php index a513e40..7bd7fd0 100644 --- a/framework/console/controllers/CreateController.php +++ b/framework/console/controllers/CreateController.php @@ -165,8 +165,8 @@ class CreateController extends Controller } /** - * @param string $path1 abosolute path - * @param string $path2 abosolute path + * @param string $path1 absolute path + * @param string $path2 absolute path * * @return string relative path */ diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index 5617c7b..c663b2b 100644 --- a/framework/console/controllers/HelpController.php +++ b/framework/console/controllers/HelpController.php @@ -12,6 +12,7 @@ namespace yii\console\controllers; use yii\base\Application; use yii\base\InlineAction; use yii\console\Controller; +use yii\util\StringHelper; /** * This command provides help information about console commands. @@ -54,16 +55,16 @@ class HelpController extends Controller } else { $result = \Yii::$application->createController($args[0]); if ($result === false) { - echo "Unknown command: " . $args[0] . "\n"; + echo "\nError: no help for unknown command \"{$args[0]}\".\n"; return 1; } - list($controller, $action) = $result; + list($controller, $actionID) = $result; - if ($action === '') { + if ($actionID === '') { $status = $this->getControllerHelp($controller); } else { - $status = $this->getActionHelp($controller, $action); + $status = $this->getActionHelp($controller, $actionID); } } return $status; @@ -87,13 +88,13 @@ class HelpController extends Controller */ public function getActions($controller) { - $actions = array_keys($controller->actionMap); + $actions = array_keys($controller->actions()); $class = new \ReflectionClass($controller); foreach ($class->getMethods() as $method) { /** @var $method \ReflectionMethod */ $name = $method->getName(); - if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0) { - $actions[] = lcfirst(substr($name, 6)); + if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0 && $name !== 'actions') { + $actions[] = StringHelper::camel2id(substr($name, 6)); } } sort($actions); @@ -107,11 +108,7 @@ class HelpController extends Controller */ protected function getModuleCommands($module) { - if ($module instanceof Application) { - $prefix = ''; - } else { - $prefix = $module->getUniqueId() . '/'; - } + $prefix = $module instanceof Application ? '' : $module->getUniqueID() . '/'; $commands = array(); foreach (array_keys($module->controllerMap) as $id) { @@ -145,12 +142,12 @@ class HelpController extends Controller { $commands = $this->getCommands(); if ($commands !== array()) { - echo "\n Usage: yiic [...options...]\n\n"; - echo "The following commands are available:\n"; + echo "\nUsage: yiic [...options...]\n\n"; + echo "The following commands are available:\n\n"; foreach ($commands as $command) { - echo " - $command\n"; + echo " * $command\n"; } - echo "\nTo see individual command help, enter:\n"; + echo "\nTo see the help of each command, enter:\n"; echo "\n yiic help \n"; } else { echo "\nNo commands are found.\n"; @@ -195,7 +192,7 @@ class HelpController extends Controller $prefix = $controller->getUniqueId(); foreach ($actions as $action) { if ($controller->defaultAction === $action) { - echo " * $prefix/$action (default)\n"; + echo " * $prefix (default)\n"; } else { echo " * $prefix/$action\n"; } diff --git a/framework/util/ConsoleHelper.php b/framework/util/ConsoleHelper.php index 9333b3c..f07ead0 100644 --- a/framework/util/ConsoleHelper.php +++ b/framework/util/ConsoleHelper.php @@ -10,7 +10,7 @@ namespace yii\util; /** - * ConsoleHelper provides additional unility functions for console applications. + * ConsoleHelper provides additional utility functions for console applications. * * @author Carsten Brandt * @author Alexander Makarov diff --git a/framework/yiic.php b/framework/yiic.php index 0f05183..55b9e60 100644 --- a/framework/yiic.php +++ b/framework/yiic.php @@ -1,5 +1,4 @@ '@yii/console/controllers', -); $id = 'yiic'; $basePath = __DIR__ . '/console'; -$application = new yii\console\Application($id, $basePath, $config); +$application = new yii\console\Application($id, $basePath, array( + 'controllerPath' => '@yii/console/controllers', +)); $application->run(); From 5b357d2eedef6a070d2940679d3ec48a25bb4ae3 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 31 Jan 2013 16:19:27 -0500 Subject: [PATCH 11/14] console app cleanup. --- framework/console/Controller.php | 63 ++-- .../console/controllers/MigrateController.php | 377 +++++++++------------ framework/console/controllers/ShellController.php | 149 -------- 3 files changed, 191 insertions(+), 398 deletions(-) delete mode 100644 framework/console/controllers/ShellController.php diff --git a/framework/console/Controller.php b/framework/console/Controller.php index f7155b0..ce4c233 100644 --- a/framework/console/Controller.php +++ b/framework/console/Controller.php @@ -32,6 +32,12 @@ use yii\base\InvalidRouteException; class Controller extends \yii\base\Controller { /** + * @var boolean whether the call of [[confirm()]] requires a user input. + * If false, [[confirm()]] will always return true no matter what user enters or not. + */ + public $interactive = true; + + /** * 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. @@ -80,43 +86,6 @@ class Controller extends \yii\base\Controller } /** - * Reads input via the readline PHP extension if that's available, or fgets() if readline is not installed. - * - * @param string $message to echo out before waiting for user input - * @param string $default the default string to be returned when user does not write anything. - * Defaults to null, means that default string is disabled. - * @return mixed line read as a string, or false if input has been closed - */ - public function prompt($message, $default = null) - { - if($default !== null) { - $message .= " [$default] "; - } - else { - $message .= ' '; - } - - if(extension_loaded('readline')) { - $input = readline($message); - if($input !== false) { - readline_add_history($input); - } - } - else { - echo $message; - $input = fgets(STDIN); - } - - if($input === false) { - return false; - } - else { - $input = trim($input); - return ($input === '' && $default !== null) ? $default : $input; - } - } - - /** * Asks user to confirm by typing y or n. * * @param string $message to echo out before waiting for user input @@ -125,9 +94,23 @@ class Controller extends \yii\base\Controller */ public function confirm($message, $default = false) { - echo $message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:'; + if ($this->interactive) { + echo $message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:'; + $input = trim(fgets(STDIN)); + return empty($input) ? $default : !strncasecmp($input, 'y', 1); + } else { + return true; + } + } + + public function error($message) + { + echo "\nError: $message\n"; + Yii::$application->end(1); + } - $input = trim(fgets(STDIN)); - return empty($input) ? $default : !strncasecmp($input, 'y', 1); + public function globalOptions() + { + return array(); } } \ No newline at end of file diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index 1da8001..b0804c3 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -10,6 +10,7 @@ namespace yii\console\controllers; +use Yii; use yii\console\Controller; /** @@ -60,25 +61,25 @@ use yii\console\Controller; */ class MigrateController extends Controller { - const BASE_MIGRATION='m000000_000000_base'; + const BASE_MIGRATION = 'm000000_000000_base'; /** * @var string the directory that stores the migrations. This must be specified * in terms of a path alias, and the corresponding directory must exist. * 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. * This table will be automatically created if not exists. Defaults to 'tbl_migration'. * The table structure is: (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 * storing migration information. Defaults to 'db'. */ - public $connectionID='db'; + public $connectionID = 'db'; /** * @var string the path of the template file for generating new migrations. This * must be specified in terms of a path alias (e.g. application.migrations.template). @@ -88,23 +89,24 @@ class MigrateController extends Controller /** * @var string the default command action. It defaults to 'up'. */ - public $defaultAction='up'; + public $defaultAction = 'up'; /** * @var boolean whether to execute the migration in an interactive mode. Defaults to true. * Set this to false when performing migration in a cron job or background process. */ - public $interactive=true; + public $interactive = true; + public function beforeAction($action) { - $path = \Yii::getAlias($this->migrationPath); - if($path===false || !is_dir($path)) { - echo 'Error: The migration directory does not exist: ' . $this->migrationPath . "\n"; - \Yii::$application->end(1); + $path = Yii::getAlias($this->migrationPath); + if ($path === false || !is_dir($path)) { + echo 'Error: the migration directory does not exist "' . $this->migrationPath . "\"\n"; + return false; } - $this->migrationPath=$path; + $this->migrationPath = $path; - $yiiVersion = \Yii::getVersion(); + $yiiVersion = Yii::getVersion(); echo "\nYii Migration Tool v2.0 (based on Yii v{$yiiVersion})\n\n"; return parent::beforeAction($action); @@ -115,34 +117,32 @@ class MigrateController extends Controller */ public function actionUp($args) { - if(($migrations = $this->getNewMigrations())===array()) - { + if (($migrations = $this->getNewMigrations()) === array()) { echo "No new migration found. Your system is up-to-date.\n"; - \Yii::$application->end(); + Yii::$application->end(); } - $total=count($migrations); - $step=isset($args[0]) ? (int)$args[0] : 0; - if($step>0) { - $migrations=array_slice($migrations,0,$step); + $total = count($migrations); + $step = isset($args[0]) ? (int)$args[0] : 0; + if ($step > 0) { + $migrations = array_slice($migrations, 0, $step); } - $n=count($migrations); - if($n===$total) - echo "Total $n new ".($n===1 ? 'migration':'migrations')." to be applied:\n"; + $n = count($migrations); + if ($n === $total) + echo "Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n"; else - echo "Total $n out of $total new ".($total===1 ? 'migration':'migrations')." to be applied:\n"; + { + echo "Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n"; + } - foreach($migrations as $migration) + foreach ($migrations as $migration) echo " $migration\n"; echo "\n"; - if($this->confirm('Apply the above '.($n===1 ? 'migration':'migrations')."?")) - { - foreach($migrations as $migration) - { - if($this->migrateUp($migration)===false) - { + if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { + foreach ($migrations as $migration) { + if ($this->migrateUp($migration) === false) { echo "\nMigration failed. All later migrations are canceled.\n"; return; } @@ -153,29 +153,25 @@ class MigrateController extends Controller public function actionDown($args) { - $step=isset($args[0]) ? (int)$args[0] : 1; - if($step<1) + $step = isset($args[0]) ? (int)$args[0] : 1; + if ($step < 1) die("Error: The step parameter must be greater than 0.\n"); - if(($migrations=$this->getMigrationHistory($step))===array()) - { + if (($migrations = $this->getMigrationHistory($step)) === array()) { echo "No migration has been done before.\n"; return; } - $migrations=array_keys($migrations); + $migrations = array_keys($migrations); - $n=count($migrations); - echo "Total $n ".($n===1 ? 'migration':'migrations')." to be reverted:\n"; - foreach($migrations as $migration) + $n = count($migrations); + echo "Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n"; + foreach ($migrations as $migration) echo " $migration\n"; echo "\n"; - if($this->confirm('Revert the above '.($n===1 ? 'migration':'migrations')."?")) - { - foreach($migrations as $migration) - { - if($this->migrateDown($migration)===false) - { + if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { + foreach ($migrations as $migration) { + if ($this->migrateDown($migration) === false) { echo "\nMigration failed. All later migrations are canceled.\n"; return; } @@ -186,37 +182,31 @@ class MigrateController extends Controller public function actionRedo($args) { - $step=isset($args[0]) ? (int)$args[0] : 1; - if($step<1) + $step = isset($args[0]) ? (int)$args[0] : 1; + if ($step < 1) die("Error: The step parameter must be greater than 0.\n"); - if(($migrations=$this->getMigrationHistory($step))===array()) - { + if (($migrations = $this->getMigrationHistory($step)) === array()) { echo "No migration has been done before.\n"; return; } - $migrations=array_keys($migrations); + $migrations = array_keys($migrations); - $n=count($migrations); - echo "Total $n ".($n===1 ? 'migration':'migrations')." to be redone:\n"; - foreach($migrations as $migration) + $n = count($migrations); + echo "Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n"; + foreach ($migrations as $migration) echo " $migration\n"; echo "\n"; - if($this->confirm('Redo the above '.($n===1 ? 'migration':'migrations')."?")) - { - foreach($migrations as $migration) - { - if($this->migrateDown($migration)===false) - { + if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { + foreach ($migrations as $migration) { + if ($this->migrateDown($migration) === false) { echo "\nMigration failed. All later migrations are canceled.\n"; return; } } - foreach(array_reverse($migrations) as $migration) - { - if($this->migrateUp($migration)===false) - { + foreach (array_reverse($migrations) as $migration) { + if ($this->migrateUp($migration) === false) { echo "\nMigration failed. All later migrations are canceled.\n"; return; } @@ -227,35 +217,31 @@ class MigrateController extends Controller public function actionTo($args) { - if(isset($args[0])) - $version=$args[0]; + if (isset($args[0])) + $version = $args[0]; else $this->usageError('Please specify which version to migrate to.'); - $originalVersion=$version; - if(preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/',$version,$matches)) - $version='m'.$matches[1]; + $originalVersion = $version; + if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) + $version = 'm' . $matches[1]; 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"); // try migrate up - $migrations=$this->getNewMigrations(); - foreach($migrations as $i=>$migration) - { - if(strpos($migration,$version.'_')===0) - { - $this->actionUp(array($i+1)); + $migrations = $this->getNewMigrations(); + foreach ($migrations as $i => $migration) { + if (strpos($migration, $version . '_') === 0) { + $this->actionUp(array($i + 1)); return; } } // try migrate down - $migrations=array_keys($this->getMigrationHistory(-1)); - foreach($migrations as $i=>$migration) - { - if(strpos($migration,$version.'_')===0) - { - if($i===0) + $migrations = array_keys($this->getMigrationHistory(-1)); + foreach ($migrations as $i => $migration) { + if (strpos($migration, $version . '_') === 0) { + if ($i === 0) echo "Already at '$originalVersion'. Nothing needs to be done.\n"; else $this->actionDown(array($i)); @@ -268,32 +254,28 @@ class MigrateController extends Controller public function actionMark($args) { - if(isset($args[0])) - $version=$args[0]; + if (isset($args[0])) + $version = $args[0]; else $this->usageError('Please specify which version to mark to.'); - $originalVersion=$version; - if(preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/',$version,$matches)) - $version='m'.$matches[1]; + $originalVersion = $version; + if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) + $version = 'm' . $matches[1]; 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"); - $db=$this->getDb(); + $db = $this->getDb(); // try mark up - $migrations=$this->getNewMigrations(); - foreach($migrations as $i=>$migration) - { - if(strpos($migration,$version.'_')===0) - { - if($this->confirm("Set migration history at $originalVersion?")) - { - $command=$db->createCommand(); - for($j=0;$j<=$i;++$j) - { + $migrations = $this->getNewMigrations(); + foreach ($migrations as $i => $migration) { + if (strpos($migration, $version . '_') === 0) { + if ($this->confirm("Set migration history at $originalVersion?")) { + $command = $db->createCommand(); + for ($j = 0; $j <= $i; ++$j) { $command->insert($this->migrationTable, array( - 'version'=>$migrations[$j], - 'apply_time'=>time(), + 'version' => $migrations[$j], + 'apply_time' => time(), )); } echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n"; @@ -303,20 +285,16 @@ class MigrateController extends Controller } // try mark down - $migrations=array_keys($this->getMigrationHistory(-1)); - foreach($migrations as $i=>$migration) - { - if(strpos($migration,$version.'_')===0) - { - if($i===0) + $migrations = array_keys($this->getMigrationHistory(-1)); + foreach ($migrations as $i => $migration) { + if (strpos($migration, $version . '_') === 0) { + if ($i === 0) echo "Already at '$originalVersion'. Nothing needs to be done.\n"; - else - { - if($this->confirm("Set migration history at $originalVersion?")) - { - $command=$db->createCommand(); - for($j=0;$j<$i;++$j) - $command->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$migrations[$j])); + else { + if ($this->confirm("Set migration history at $originalVersion?")) { + $command = $db->createCommand(); + for ($j = 0; $j < $i; ++$j) + $command->delete($this->migrationTable, $db->quoteColumnName('version') . '=:version', array(':version' => $migrations[$j])); echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n"; } } @@ -329,125 +307,107 @@ class MigrateController extends Controller public function actionHistory($args) { - $limit=isset($args[0]) ? (int)$args[0] : -1; - $migrations=$this->getMigrationHistory($limit); - if($migrations===array()) + $limit = isset($args[0]) ? (int)$args[0] : -1; + $migrations = $this->getMigrationHistory($limit); + if ($migrations === array()) echo "No migration has been done before.\n"; - else - { - $n=count($migrations); - if($limit>0) - echo "Showing the last $n applied ".($n===1 ? 'migration' : 'migrations').":\n"; + else { + $n = count($migrations); + if ($limit > 0) + echo "Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n"; else - echo "Total $n ".($n===1 ? 'migration has' : 'migrations have')." been applied before:\n"; - foreach($migrations as $version=>$time) - echo " (".date('Y-m-d H:i:s',$time).') '.$version."\n"; + echo "Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n"; + foreach ($migrations as $version => $time) + echo " (" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n"; } } public function actionNew($args) { - $limit=isset($args[0]) ? (int)$args[0] : -1; - $migrations=$this->getNewMigrations(); - if($migrations===array()) + $limit = isset($args[0]) ? (int)$args[0] : -1; + $migrations = $this->getNewMigrations(); + if ($migrations === array()) echo "No new migrations found. Your system is up-to-date.\n"; - else - { - $n=count($migrations); - if($limit>0 && $n>$limit) - { - $migrations=array_slice($migrations,0,$limit); - echo "Showing $limit out of $n new ".($n===1 ? 'migration' : 'migrations').":\n"; - } - else - echo "Found $n new ".($n===1 ? 'migration' : 'migrations').":\n"; - - foreach($migrations as $migration) - echo " ".$migration."\n"; + else { + $n = count($migrations); + if ($limit > 0 && $n > $limit) { + $migrations = array_slice($migrations, 0, $limit); + echo "Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n"; + } else + echo "Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n"; + + foreach ($migrations as $migration) + echo " " . $migration . "\n"; } } public function actionCreate($args) { - if(isset($args[0])) - $name=$args[0]; + if (isset($args[0])) + $name = $args[0]; else $this->usageError('Please provide the name of the new migration.'); - if(!preg_match('/^\w+$/',$name)) + if (!preg_match('/^\w+$/', $name)) die("Error: The name of the migration must contain letters, digits and/or underscore characters only.\n"); - $name='m'.gmdate('ymd_His').'_'.$name; - $content=strtr($this->getTemplate(), array('{ClassName}'=>$name)); - $file=$this->migrationPath.DIRECTORY_SEPARATOR.$name.'.php'; + $name = 'm' . gmdate('ymd_His') . '_' . $name; + $content = strtr($this->getTemplate(), array('{ClassName}' => $name)); + $file = $this->migrationPath . DIRECTORY_SEPARATOR . $name . '.php'; - if($this->confirm("Create new migration '$file'?")) - { + if ($this->confirm("Create new migration '$file'?")) { file_put_contents($file, $content); echo "New migration created successfully.\n"; } } - public function confirm($message) - { - if(!$this->interactive) - return true; - return parent::confirm($message); - } - protected function migrateUp($class) { - if($class===self::BASE_MIGRATION) + if ($class === self::BASE_MIGRATION) return; echo "*** applying $class\n"; - $start=microtime(true); - $migration=$this->instantiateMigration($class); - if($migration->up()!==false) - { + $start = microtime(true); + $migration = $this->instantiateMigration($class); + if ($migration->up() !== false) { $this->getDb()->createCommand()->insert($this->migrationTable, array( - 'version'=>$class, - 'apply_time'=>time(), + 'version' => $class, + 'apply_time' => time(), )); - $time=microtime(true)-$start; - echo "*** applied $class (time: ".sprintf("%.3f",$time)."s)\n\n"; - } - else - { - $time=microtime(true)-$start; - echo "*** failed to apply $class (time: ".sprintf("%.3f",$time)."s)\n\n"; + $time = microtime(true) - $start; + echo "*** applied $class (time: " . sprintf("%.3f", $time) . "s)\n\n"; + } else { + $time = microtime(true) - $start; + echo "*** failed to apply $class (time: " . sprintf("%.3f", $time) . "s)\n\n"; return false; } } protected function migrateDown($class) { - if($class===self::BASE_MIGRATION) + if ($class === self::BASE_MIGRATION) return; echo "*** reverting $class\n"; - $start=microtime(true); - $migration=$this->instantiateMigration($class); - if($migration->down()!==false) - { - $db=$this->getDb(); - $db->createCommand()->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$class)); - $time=microtime(true)-$start; - echo "*** reverted $class (time: ".sprintf("%.3f",$time)."s)\n\n"; - } - else - { - $time=microtime(true)-$start; - echo "*** failed to revert $class (time: ".sprintf("%.3f",$time)."s)\n\n"; + $start = microtime(true); + $migration = $this->instantiateMigration($class); + if ($migration->down() !== false) { + $db = $this->getDb(); + $db->createCommand()->delete($this->migrationTable, $db->quoteColumnName('version') . '=:version', array(':version' => $class)); + $time = microtime(true) - $start; + echo "*** reverted $class (time: " . sprintf("%.3f", $time) . "s)\n\n"; + } else { + $time = microtime(true) - $start; + echo "*** failed to revert $class (time: " . sprintf("%.3f", $time) . "s)\n\n"; return false; } } protected function instantiateMigration($class) { - $file=$this->migrationPath.DIRECTORY_SEPARATOR.$class.'.php'; + $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; require_once($file); - $migration=new $class; + $migration = new $class; $migration->setDb($this->getDb()); return $migration; } @@ -456,11 +416,12 @@ class MigrateController extends Controller * @var CDbConnection */ private $_db; + protected function getDb() { - if($this->_db!==null) + if ($this->_db !== null) return $this->_db; - else if(($this->_db=\Yii::$application->getComponent($this->connectionID)) instanceof CDbConnection) + else if (($this->_db = Yii::$application->getComponent($this->connectionID)) instanceof CDbConnection) return $this->_db; else die("Error: CMigrationCommand.connectionID '{$this->connectionID}' is invalid. Please make sure it refers to the ID of a CDbConnection application component.\n"); @@ -468,9 +429,8 @@ class MigrateController extends Controller protected function getMigrationHistory($limit) { - $db=$this->getDb(); - if($db->schema->getTable($this->migrationTable)===null) - { + $db = $this->getDb(); + if ($db->schema->getTable($this->migrationTable) === null) { $this->createMigrationHistoryTable(); } return CHtml::listData($db->createCommand() @@ -483,34 +443,33 @@ class MigrateController extends Controller protected function createMigrationHistoryTable() { - $db=$this->getDb(); - echo 'Creating migration history table "'.$this->migrationTable.'"...'; - $db->createCommand()->createTable($this->migrationTable,array( - 'version'=>'string NOT NULL PRIMARY KEY', - 'apply_time'=>'integer', + $db = $this->getDb(); + echo 'Creating migration history table "' . $this->migrationTable . '"...'; + $db->createCommand()->createTable($this->migrationTable, array( + 'version' => 'string NOT NULL PRIMARY KEY', + 'apply_time' => 'integer', )); - $db->createCommand()->insert($this->migrationTable,array( - 'version'=>self::BASE_MIGRATION, - 'apply_time'=>time(), + $db->createCommand()->insert($this->migrationTable, array( + 'version' => self::BASE_MIGRATION, + 'apply_time' => time(), )); echo "done.\n"; } protected function getNewMigrations() { - $applied=array(); - foreach($this->getMigrationHistory(-1) as $version=>$time) - $applied[substr($version,1,13)]=true; - - $migrations=array(); - $handle=opendir($this->migrationPath); - while(($file=readdir($handle))!==false) - { - if($file==='.' || $file==='..') + $applied = array(); + foreach ($this->getMigrationHistory(-1) as $version => $time) + $applied[substr($version, 1, 13)] = true; + + $migrations = array(); + $handle = opendir($this->migrationPath); + while (($file = readdir($handle)) !== false) { + if ($file === '.' || $file === '..') continue; - $path=$this->migrationPath.DIRECTORY_SEPARATOR.$file; - if(preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/',$file,$matches) && is_file($path) && !isset($applied[$matches[2]])) - $migrations[]=$matches[1]; + $path = $this->migrationPath . DIRECTORY_SEPARATOR . $file; + if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path) && !isset($applied[$matches[2]])) + $migrations[] = $matches[1]; } closedir($handle); sort($migrations); @@ -519,8 +478,8 @@ class MigrateController extends Controller protected function getTemplate() { - if($this->templateFile!==null) - return file_get_contents(Yii::getPathOfAlias($this->templateFile).'.php'); + if ($this->templateFile !== null) + return file_get_contents(Yii::getPathOfAlias($this->templateFile) . '.php'); else return << - * @link http://www.yiiframework.com/ - * @copyright Copyright © 2008 Yii Software LLC - * @license http://www.yiiframework.com/license/ - */ - -namespace yii\console\controllers; - -use yii\console\Controller; - -/** - * This command executes the specified Web application and provides a shell for interaction. - * - * @property string $help The help information for the shell command. - * - * @author Qiang Xue - * @since 2.0 - */ -class ShellController extends Controller -{ - /** - * @return string the help information for the shell command - */ - public function getHelp() - { - return <<usageError("{$args[0]} does not exist or is not an entry script file."); - - // fake the web server setting - $cwd=getcwd(); - chdir(dirname($entryScript)); - $_SERVER['SCRIPT_NAME']='/'.basename($entryScript); - $_SERVER['REQUEST_URI']=$_SERVER['SCRIPT_NAME']; - $_SERVER['SCRIPT_FILENAME']=$entryScript; - $_SERVER['HTTP_HOST']='localhost'; - $_SERVER['SERVER_NAME']='localhost'; - $_SERVER['SERVER_PORT']=80; - - // reset context to run the web application - restore_error_handler(); - restore_exception_handler(); - Yii::setApplication(null); - Yii::setPathOfAlias('application',null); - - ob_start(); - $config=require($entryScript); - ob_end_clean(); - - // oops, the entry script turns out to be a config file - if(is_array($config)) - { - chdir($cwd); - $_SERVER['SCRIPT_NAME']='/index.php'; - $_SERVER['REQUEST_URI']=$_SERVER['SCRIPT_NAME']; - $_SERVER['SCRIPT_FILENAME']=$cwd.DIRECTORY_SEPARATOR.'index.php'; - Yii::createWebApplication($config); - } - - restore_error_handler(); - restore_exception_handler(); - - $yiiVersion=Yii::getVersion(); - echo <<runShell(); - } - - protected function runShell() - { - // disable E_NOTICE so that the shell is more friendly - error_reporting(E_ALL ^ E_NOTICE); - - $_runner_=new CConsoleCommandRunner; - $_runner_->addCommands(dirname(__FILE__).'/shell'); - $_runner_->addCommands(Yii::getPathOfAlias('application.commands.shell')); - if(($_path_=@getenv('YIIC_SHELL_COMMAND_PATH'))!==false) - $_runner_->addCommands($_path_); - $_commands_=$_runner_->commands; - $log=\Yii::$application->log; - - while(($_line_=$this->prompt("\n>>"))!==false) - { - $_line_=trim($_line_); - if($_line_==='exit') - return; - try - { - $_args_=preg_split('/[\s,]+/',rtrim($_line_,';'),-1,PREG_SPLIT_NO_EMPTY); - if(isset($_args_[0]) && isset($_commands_[$_args_[0]])) - { - $_command_=$_runner_->createCommand($_args_[0]); - array_shift($_args_); - $_command_->init(); - $_command_->run($_args_); - } - else - echo eval($_line_.';'); - } - catch(Exception $e) - { - if($e instanceof ShellException) - echo $e->getMessage(); - else - echo $e; - } - } - } -} - -class ShellException extends CException -{ -} \ No newline at end of file From 6fcac324104499b5f570df358a4065997538997d Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 31 Jan 2013 23:50:53 -0500 Subject: [PATCH 12/14] error handling cleanup. --- framework/YiiBase.php | 5 + framework/base/Application.php | 193 ++++++++++++++------- framework/base/ErrorHandler.php | 65 +------ framework/console/Application.php | 8 +- framework/console/Controller.php | 2 +- framework/console/controllers/HelpController.php | 4 +- .../console/controllers/MigrateController.php | 139 +++++++++------ tests/unit/bootstrap.php | 1 - 8 files changed, 231 insertions(+), 186 deletions(-) diff --git a/framework/YiiBase.php b/framework/YiiBase.php index 14e0f44..d01648c 100644 --- a/framework/YiiBase.php +++ b/framework/YiiBase.php @@ -29,6 +29,11 @@ defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 0); * This constant defines the framework installation directory. */ defined('YII_PATH') or define('YII_PATH', __DIR__); +/** + * This constant defines whether error handling should be enabled. Defaults to true. + */ +defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true); + /** * YiiBase is the core helper class for the Yii framework. diff --git a/framework/base/Application.php b/framework/base/Application.php index 6203d11..e797ab7 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -11,7 +11,6 @@ namespace yii\base; use Yii; use yii\util\FileHelper; -use yii\base\InvalidCallException; /** * Application is the base class for all application classes. @@ -76,11 +75,9 @@ class Application extends Module */ public $sourceLanguage = 'en_us'; /** - * @var array IDs of application components that need to be loaded when the application starts. - * The default value is `array('errorHandler')`, which loads the [[errorHandler]] component - * to ensure errors and exceptions can be handled nicely. + * @var array IDs of the components that need to be loaded when the application starts. */ - public $preload = array('errorHandler'); + public $preload = array(); /** * @var Controller the currently active controller instance */ @@ -110,8 +107,15 @@ class Application extends Module Yii::$application = $this; $this->id = $id; $this->setBasePath($basePath); + + if (YII_ENABLE_ERROR_HANDLER) { + set_exception_handler(array($this, 'handleException')); + set_error_handler(array($this, 'handleError'), error_reporting()); + } + $this->registerDefaultAliases(); $this->registerCoreComponents(); + Component::__construct($config); } @@ -253,61 +257,61 @@ class Application extends Module date_default_timezone_set($value); } -// /** -// * Returns the security manager component. -// * @return SecurityManager the security manager application component. -// */ -// public function getSecurityManager() -// { -// return $this->getComponent('securityManager'); -// } -// -// /** -// * Returns the locale instance. -// * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used. -// * @return CLocale the locale instance -// */ -// public function getLocale($localeID = null) -// { -// return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID); -// } -// -// /** -// * @return CNumberFormatter the locale-dependent number formatter. -// * The current {@link getLocale application locale} will be used. -// */ -// public function getNumberFormatter() -// { -// return $this->getLocale()->getNumberFormatter(); -// } -// -// /** -// * Returns the locale-dependent date formatter. -// * @return CDateFormatter the locale-dependent date formatter. -// * The current {@link getLocale application locale} will be used. -// */ -// public function getDateFormatter() -// { -// return $this->getLocale()->getDateFormatter(); -// } -// -// /** -// * Returns the core message translations component. -// * @return \yii\i18n\MessageSource the core message translations -// */ -// public function getCoreMessages() -// { -// return $this->getComponent('coreMessages'); -// } -// -// /** -// * Returns the application message translations component. -// * @return \yii\i18n\MessageSource the application message translations -// */ -// public function getMessages() -// { -// return $this->getComponent('messages'); -// } + // /** + // * Returns the security manager component. + // * @return SecurityManager the security manager application component. + // */ + // public function getSecurityManager() + // { + // return $this->getComponent('securityManager'); + // } + // + // /** + // * Returns the locale instance. + // * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used. + // * @return CLocale the locale instance + // */ + // public function getLocale($localeID = null) + // { + // return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID); + // } + // + // /** + // * @return CNumberFormatter the locale-dependent number formatter. + // * The current {@link getLocale application locale} will be used. + // */ + // public function getNumberFormatter() + // { + // return $this->getLocale()->getNumberFormatter(); + // } + // + // /** + // * Returns the locale-dependent date formatter. + // * @return CDateFormatter the locale-dependent date formatter. + // * The current {@link getLocale application locale} will be used. + // */ + // public function getDateFormatter() + // { + // return $this->getLocale()->getDateFormatter(); + // } + // + // /** + // * Returns the core message translations component. + // * @return \yii\i18n\MessageSource the core message translations + // */ + // public function getCoreMessages() + // { + // return $this->getComponent('coreMessages'); + // } + // + // /** + // * Returns the application message translations component. + // * @return \yii\i18n\MessageSource the application message translations + // */ + // public function getMessages() + // { + // return $this->getComponent('messages'); + // } /** * Returns the database connection component. @@ -390,4 +394,73 @@ class Application extends Module ), )); } + + /** + * Handles PHP execution errors such as warnings, notices. + * + * This method is used as a PHP error handler. It will simply raise an `ErrorException`. + * + * @param integer $code the level of the error raised + * @param string $message the error message + * @param string $file the filename that the error was raised in + * @param integer $line the line number the error was raised at + * @throws \ErrorException the error exception + */ + public function handleError($code, $message, $file, $line) + { + if (error_reporting() !== 0) { + throw new \ErrorException($message, 0, $code, $file, $line); + } + } + + /** + * Handles uncaught PHP exceptions. + * + * This method is implemented as a PHP exception handler. It requires + * that constant YII_ENABLE_ERROR_HANDLER be defined true. + * + * @param \Exception $exception exception that is not caught + */ + public function handleException($exception) + { + // disable error capturing to avoid recursive errors while handling exceptions + restore_error_handler(); + restore_exception_handler(); + + try { + $this->logException($exception); + + if (($handler = $this->getErrorHandler()) !== null) { + $handler->handle($exception); + } else { + $message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage() . "\n"; + echo PHP_SAPI === 'cli' ? $message : '
    ' . $message . '
    '; + } + + $this->end(1); + + } catch(\Exception $e) { + // exception could be thrown in end() or ErrorHandler::handle() + $msg = (string)$e; + $msg .= "\nPrevious exception:\n"; + $msg .= (string)$exception; + $msg .= "\n\$_SERVER = " . var_export($_SERVER, true); + error_log($msg); + exit(1); + } + } + + // todo: to be polished + protected function logException($exception) + { + $category = get_class($exception); + if ($exception instanceof HttpException) { + /** @var $exception HttpException */ + $category .= '\\' . $exception->statusCode; + } elseif ($exception instanceof \ErrorException) { + /** @var $exception \ErrorException */ + $category .= '\\' . $exception->getSeverity(); + } + Yii::error((string)$exception, $category); + } } diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index 5b48fbf..e544a49 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -54,66 +54,18 @@ class ErrorHandler extends Component public $exception; - public function init() - { - set_exception_handler(array($this, 'handleException')); - set_error_handler(array($this, 'handleError'), error_reporting()); - } - - /** - * Handles PHP execution errors such as warnings, notices. - * - * This method is used as a PHP error handler. It will simply raise an `ErrorException`. - * - * @param integer $code the level of the error raised - * @param string $message the error message - * @param string $file the filename that the error was raised in - * @param integer $line the line number the error was raised at - * @throws \ErrorException the error exception - */ - public function handleError($code, $message, $file, $line) - { - if(error_reporting()!==0) { - throw new \ErrorException($message, 0, $code, $file, $line); - } - } - /** * @param \Exception $exception */ - public function handleException($exception) + public function handle($exception) { - // disable error capturing to avoid recursive errors while handling exceptions - restore_error_handler(); - restore_exception_handler(); - $this->exception = $exception; - $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } - try { - $this->render($exception); - } catch (\Exception $e) { - // use the most primitive way to display exception thrown in the error view - $this->renderAsText($e); - } - - - try { - \Yii::$application->end(1); - } catch (Exception $e2) { - // use the most primitive way to log error occurred in end() - $msg = get_class($e2) . ': ' . $e2->getMessage() . ' (' . $e2->getFile() . ':' . $e2->getLine() . ")\n"; - $msg .= $e2->getTraceAsString() . "\n"; - $msg .= "Previous error:\n"; - $msg .= $e2->getTraceAsString() . "\n"; - $msg .= '$_SERVER=' . var_export($_SERVER, true); - error_log($msg); - exit(1); - } + $this->render($exception); } protected function render($exception) @@ -282,19 +234,6 @@ class ErrorHandler extends Component return htmlspecialchars($text, ENT_QUOTES, \Yii::$application->charset); } - public function logException($exception) - { - $category = get_class($exception); - if ($exception instanceof HttpException) { - /** @var $exception HttpException */ - $category .= '\\' . $exception->statusCode; - } elseif ($exception instanceof \ErrorException) { - /** @var $exception \ErrorException */ - $category .= '\\' . $exception->getSeverity(); - } - \Yii::error((string)$exception, $category); - } - public function clearOutput() { // the following manual level counting is to deal with zlib.output_compression set to On diff --git a/framework/console/Application.php b/framework/console/Application.php index 6ad40cc..64c17e5 100644 --- a/framework/console/Application.php +++ b/framework/console/Application.php @@ -85,7 +85,6 @@ class Application extends \yii\base\Application * Processes the request. * 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) - * @throws Exception if the route cannot be resolved into a controller */ public function processRequest() { @@ -99,7 +98,6 @@ class Application extends \yii\base\Application } } - /** * Runs a controller action specified by a route. * This method parses the specified route and creates the corresponding child module(s), controller and action @@ -108,7 +106,6 @@ class Application extends \yii\base\Application * @param string $route the route that specifies 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. - * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully */ public function runAction($route, $params = array()) { @@ -151,4 +148,9 @@ class Application extends \yii\base\Application ), )); } + + public function usageError($message) + { + + } } diff --git a/framework/console/Controller.php b/framework/console/Controller.php index ce4c233..16968f2 100644 --- a/framework/console/Controller.php +++ b/framework/console/Controller.php @@ -103,7 +103,7 @@ class Controller extends \yii\base\Controller } } - public function error($message) + public function usageError($message) { echo "\nError: $message\n"; Yii::$application->end(1); diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index c663b2b..6e4b397 100644 --- a/framework/console/controllers/HelpController.php +++ b/framework/console/controllers/HelpController.php @@ -55,7 +55,7 @@ class HelpController extends Controller } else { $result = \Yii::$application->createController($args[0]); if ($result === false) { - echo "\nError: no help for unknown command \"{$args[0]}\".\n"; + echo "Error: no help for unknown command \"{$args[0]}\".\n"; return 1; } @@ -213,7 +213,7 @@ class HelpController extends Controller { $action = $controller->createAction($actionID); if ($action === null) { - echo "Unknown sub-command: " . $controller->getUniqueId() . "/$actionID\n"; + echo 'Error: no help for unknown sub-command "' . $controller->getUniqueId() . "/$actionID\".\n"; return 1; } if ($action instanceof InlineAction) { diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index b0804c3..e104856 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -99,17 +99,19 @@ class MigrateController extends Controller public function beforeAction($action) { - $path = Yii::getAlias($this->migrationPath); - if ($path === false || !is_dir($path)) { - echo 'Error: the migration directory does not exist "' . $this->migrationPath . "\"\n"; + if (parent::beforeAction($action)) { + $path = Yii::getAlias($this->migrationPath); + if ($path === false || !is_dir($path)) { + echo 'Error: the migration directory does not exist "' . $this->migrationPath . "\"\n"; + return false; + } + $this->migrationPath = $path; + $version = Yii::getVersion(); + echo "\nYii Migration Tool v2.0 (based on Yii v{$version})\n\n"; + return true; + } else { return false; } - $this->migrationPath = $path; - - $yiiVersion = Yii::getVersion(); - echo "\nYii Migration Tool v2.0 (based on Yii v{$yiiVersion})\n\n"; - - return parent::beforeAction($action); } /** @@ -129,15 +131,15 @@ class MigrateController extends Controller } $n = count($migrations); - if ($n === $total) + if ($n === $total) { echo "Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n"; - else - { - echo "Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n"; - } + } else { + echo "Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n"; + } - foreach ($migrations as $migration) + foreach ($migrations as $migration) { echo " $migration\n"; + } echo "\n"; if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { @@ -154,8 +156,9 @@ class MigrateController extends Controller public function actionDown($args) { $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"); + } if (($migrations = $this->getMigrationHistory($step)) === array()) { echo "No migration has been done before.\n"; @@ -165,8 +168,9 @@ class MigrateController extends Controller $n = count($migrations); echo "Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n"; - foreach ($migrations as $migration) + foreach ($migrations as $migration) { echo " $migration\n"; + } echo "\n"; if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { @@ -183,8 +187,9 @@ class MigrateController extends Controller public function actionRedo($args) { $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"); + } if (($migrations = $this->getMigrationHistory($step)) === array()) { echo "No migration has been done before.\n"; @@ -194,8 +199,9 @@ class MigrateController extends Controller $n = count($migrations); echo "Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n"; - foreach ($migrations as $migration) + foreach ($migrations as $migration) { echo " $migration\n"; + } echo "\n"; if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) { @@ -217,16 +223,18 @@ class MigrateController extends Controller public function actionTo($args) { - if (isset($args[0])) + if (isset($args[0])) { $version = $args[0]; - else + } else { $this->usageError('Please specify which version to migrate to.'); + } $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]; - 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"); + } // try migrate up $migrations = $this->getNewMigrations(); @@ -241,10 +249,11 @@ class MigrateController extends Controller $migrations = array_keys($this->getMigrationHistory(-1)); foreach ($migrations as $i => $migration) { if (strpos($migration, $version . '_') === 0) { - if ($i === 0) + if ($i === 0) { echo "Already at '$originalVersion'. Nothing needs to be done.\n"; - else + } else { $this->actionDown(array($i)); + } return; } } @@ -254,15 +263,17 @@ class MigrateController extends Controller public function actionMark($args) { - if (isset($args[0])) + if (isset($args[0])) { $version = $args[0]; - else + } else { $this->usageError('Please specify which version to mark to.'); + } $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]; - 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"); + } $db = $this->getDb(); @@ -288,13 +299,14 @@ class MigrateController extends Controller $migrations = array_keys($this->getMigrationHistory(-1)); foreach ($migrations as $i => $migration) { if (strpos($migration, $version . '_') === 0) { - if ($i === 0) + if ($i === 0) { echo "Already at '$originalVersion'. Nothing needs to be done.\n"; - else { + } else { if ($this->confirm("Set migration history at $originalVersion?")) { $command = $db->createCommand(); - for ($j = 0; $j < $i; ++$j) + for ($j = 0; $j < $i; ++$j) { $command->delete($this->migrationTable, $db->quoteColumnName('version') . '=:version', array(':version' => $migrations[$j])); + } echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n"; } } @@ -309,16 +321,18 @@ class MigrateController extends Controller { $limit = isset($args[0]) ? (int)$args[0] : -1; $migrations = $this->getMigrationHistory($limit); - if ($migrations === array()) + if ($migrations === array()) { echo "No migration has been done before.\n"; - else { + } else { $n = count($migrations); - if ($limit > 0) + if ($limit > 0) { echo "Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n"; - else + } else { echo "Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n"; - foreach ($migrations as $version => $time) + } + foreach ($migrations as $version => $time) { echo " (" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n"; + } } } @@ -326,30 +340,34 @@ class MigrateController extends Controller { $limit = isset($args[0]) ? (int)$args[0] : -1; $migrations = $this->getNewMigrations(); - if ($migrations === array()) + if ($migrations === array()) { echo "No new migrations found. Your system is up-to-date.\n"; - else { + } else { $n = count($migrations); if ($limit > 0 && $n > $limit) { $migrations = array_slice($migrations, 0, $limit); echo "Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n"; - } else + } else { echo "Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n"; + } - foreach ($migrations as $migration) + foreach ($migrations as $migration) { echo " " . $migration . "\n"; + } } } public function actionCreate($args) { - if (isset($args[0])) + if (isset($args[0])) { $name = $args[0]; - else + } else { $this->usageError('Please provide the name of the new migration.'); + } - if (!preg_match('/^\w+$/', $name)) + if (!preg_match('/^\w+$/', $name)) { die("Error: The name of the migration must contain letters, digits and/or underscore characters only.\n"); + } $name = 'm' . gmdate('ymd_His') . '_' . $name; $content = strtr($this->getTemplate(), array('{ClassName}' => $name)); @@ -363,8 +381,9 @@ class MigrateController extends Controller protected function migrateUp($class) { - if ($class === self::BASE_MIGRATION) + if ($class === self::BASE_MIGRATION) { return; + } echo "*** applying $class\n"; $start = microtime(true); @@ -385,8 +404,9 @@ class MigrateController extends Controller protected function migrateDown($class) { - if ($class === self::BASE_MIGRATION) + if ($class === self::BASE_MIGRATION) { return; + } echo "*** reverting $class\n"; $start = microtime(true); @@ -419,12 +439,15 @@ class MigrateController extends Controller protected function getDb() { - if ($this->_db !== null) - return $this->_db; - else if (($this->_db = Yii::$application->getComponent($this->connectionID)) instanceof CDbConnection) + if ($this->_db !== null) { return $this->_db; - else - die("Error: CMigrationCommand.connectionID '{$this->connectionID}' is invalid. Please make sure it refers to the ID of a CDbConnection application component.\n"); + } else { + if (($this->_db = Yii::$application->getComponent($this->connectionID)) instanceof CDbConnection) { + return $this->_db; + } else { + die("Error: CMigrationCommand.connectionID '{$this->connectionID}' is invalid. Please make sure it refers to the ID of a CDbConnection application component.\n"); + } + } } protected function getMigrationHistory($limit) @@ -459,17 +482,20 @@ class MigrateController extends Controller protected function getNewMigrations() { $applied = array(); - foreach ($this->getMigrationHistory(-1) as $version => $time) + foreach ($this->getMigrationHistory(-1) as $version => $time) { $applied[substr($version, 1, 13)] = true; + } $migrations = array(); $handle = opendir($this->migrationPath); while (($file = readdir($handle)) !== false) { - if ($file === '.' || $file === '..') + if ($file === '.' || $file === '..') { continue; + } $path = $this->migrationPath . DIRECTORY_SEPARATOR . $file; - if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path) && !isset($applied[$matches[2]])) + if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path) && !isset($applied[$matches[2]])) { $migrations[] = $matches[1]; + } } closedir($handle); sort($migrations); @@ -478,9 +504,9 @@ class MigrateController extends Controller protected function getTemplate() { - if ($this->templateFile !== null) + if ($this->templateFile !== null) { return file_get_contents(Yii::getPathOfAlias($this->templateFile) . '.php'); - else + } else { return << Date: Fri, 1 Feb 2013 07:53:32 -0500 Subject: [PATCH 13/14] exception cleanup. --- framework/base/Application.php | 21 +++++++++++++++++-- framework/base/ErrorHandler.php | 31 +++++++++++++++-------------- framework/base/Exception.php | 12 +++++++++-- framework/base/HttpException.php | 4 ++++ framework/base/InvalidCallException.php | 7 +++++-- framework/base/InvalidConfigException.php | 7 +++++-- framework/base/InvalidRequestException.php | 12 +++++++++-- framework/base/InvalidRouteException.php | 12 +++++++++-- framework/base/NotSupportedException.php | 7 +++++-- framework/base/UnknownMethodException.php | 7 +++++-- framework/base/UnknownPropertyException.php | 7 +++++-- framework/console/Application.php | 2 +- framework/db/Exception.php | 13 +++++++----- 13 files changed, 103 insertions(+), 39 deletions(-) diff --git a/framework/base/Application.php b/framework/base/Application.php index e797ab7..f64e352 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -433,8 +433,7 @@ class Application extends Module if (($handler = $this->getErrorHandler()) !== null) { $handler->handle($exception); } else { - $message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage() . "\n"; - echo PHP_SAPI === 'cli' ? $message : '
    ' . $message . '
    '; + $this->renderException($exception); } $this->end(1); @@ -450,6 +449,24 @@ class Application extends Module } } + /** + * Renders an exception without using rich format. + * @param \Exception $exception the exception to be rendered. + */ + public function renderException($exception) + { + if ($exception instanceof Exception && ($exception->causedByUser || !YII_DEBUG)) { + $message = $exception->getName() . ': ' . $exception->getMessage(); + } else { + $message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage(); + } + if (PHP_SAPI) { + echo $message . "\n"; + } else { + echo '
    ' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '
    '; + } + } + // todo: to be polished protected function logException($exception) { diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index e544a49..0b6bf97 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -78,12 +78,20 @@ class ErrorHandler extends Component header("HTTP/1.0 $errorCode " . get_class($exception)); } if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { - $this->renderAsText($exception); + \Yii::$application->renderException($exception); } else { - $this->renderAsHtml($exception); + $view = new View($this); + if (!YII_DEBUG || $exception instanceof Exception && $exception->causedByUser) { + $viewName = $this->errorView; + } else { + $viewName = $this->exceptionView; + } + echo $view->render($viewName, array( + 'exception' => $exception, + )); } } else { - $this->renderAsText($exception); + \Yii::$application->renderException($exception); } } @@ -245,21 +253,14 @@ class ErrorHandler extends Component /** * @param \Exception $exception */ - public function renderAsText($exception) - { - if (YII_DEBUG) { - echo $exception; - } else { - echo get_class($exception) . ': ' . $exception->getMessage(); - } - } - - /** - * @param \Exception $exception - */ public function renderAsHtml($exception) { $view = new View($this); + if (!YII_DEBUG || $exception instanceof Exception && $exception->causedByUser) { + $viewName = $this->errorView; + } else { + $viewName = $this->exceptionView; + } $name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView; echo $view->render($name, array( 'exception' => $exception, diff --git a/framework/base/Exception.php b/framework/base/Exception.php index 89fa30a..ab681e2 100644 --- a/framework/base/Exception.php +++ b/framework/base/Exception.php @@ -18,8 +18,16 @@ namespace yii\base; class Exception extends \Exception { /** - * @var string the user-friend name of this exception + * @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL) */ - public $name = 'Exception'; + public $causedByUser = false; + + /** + * @return string the user-friendly name of this exception + */ + public function getName() + { + return \Yii::t('yii', 'Exception'); + } } diff --git a/framework/base/HttpException.php b/framework/base/HttpException.php index 52ac690..d2de5bc 100644 --- a/framework/base/HttpException.php +++ b/framework/base/HttpException.php @@ -25,6 +25,10 @@ class HttpException extends Exception * @var integer HTTP status code, such as 403, 404, 500, etc. */ public $statusCode; + /** + * @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL) + */ + public $causedByUser = true; /** * Constructor. diff --git a/framework/base/InvalidCallException.php b/framework/base/InvalidCallException.php index e9d81b4..a1df021 100644 --- a/framework/base/InvalidCallException.php +++ b/framework/base/InvalidCallException.php @@ -18,8 +18,11 @@ namespace yii\base; class InvalidCallException extends \Exception { /** - * @var string the user-friend name of this exception + * @return string the user-friendly name of this exception */ - public $name = 'Invalid Call Exception'; + public function getName() + { + return \Yii::t('yii', 'Invalid Call'); + } } diff --git a/framework/base/InvalidConfigException.php b/framework/base/InvalidConfigException.php index 8f292df..3c100d1 100644 --- a/framework/base/InvalidConfigException.php +++ b/framework/base/InvalidConfigException.php @@ -18,8 +18,11 @@ namespace yii\base; class InvalidConfigException extends \Exception { /** - * @var string the user-friend name of this exception + * @return string the user-friendly name of this exception */ - public $name = 'Invalid Configuration Exception'; + public function getName() + { + return \Yii::t('yii', 'Invalid Configuration'); + } } diff --git a/framework/base/InvalidRequestException.php b/framework/base/InvalidRequestException.php index 38c4115..fd468a1 100644 --- a/framework/base/InvalidRequestException.php +++ b/framework/base/InvalidRequestException.php @@ -18,8 +18,16 @@ namespace yii\base; class InvalidRequestException extends \Exception { /** - * @var string the user-friend name of this exception + * @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL) */ - public $name = 'Invalid Request Exception'; + public $causedByUser = true; + + /** + * @return string the user-friendly name of this exception + */ + public function getName() + { + return \Yii::t('yii', 'Invalid Request'); + } } diff --git a/framework/base/InvalidRouteException.php b/framework/base/InvalidRouteException.php index 6549c07..e20b2b7 100644 --- a/framework/base/InvalidRouteException.php +++ b/framework/base/InvalidRouteException.php @@ -18,8 +18,16 @@ namespace yii\base; class InvalidRouteException extends \Exception { /** - * @var string the user-friend name of this exception + * @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL) */ - public $name = 'Invalid Route Exception'; + public $causedByUser = true; + + /** + * @return string the user-friendly name of this exception + */ + public function getName() + { + return \Yii::t('yii', 'Invalid Route'); + } } diff --git a/framework/base/NotSupportedException.php b/framework/base/NotSupportedException.php index 2da008c..56e7e36 100644 --- a/framework/base/NotSupportedException.php +++ b/framework/base/NotSupportedException.php @@ -18,8 +18,11 @@ namespace yii\base; class NotSupportedException extends \Exception { /** - * @var string the user-friend name of this exception + * @return string the user-friendly name of this exception */ - public $name = 'Not Supported Exception'; + public function getName() + { + return \Yii::t('yii', 'Not Supported'); + } } diff --git a/framework/base/UnknownMethodException.php b/framework/base/UnknownMethodException.php index b88d97f..459f791 100644 --- a/framework/base/UnknownMethodException.php +++ b/framework/base/UnknownMethodException.php @@ -18,8 +18,11 @@ namespace yii\base; class UnknownMethodException extends \Exception { /** - * @var string the user-friend name of this exception + * @return string the user-friendly name of this exception */ - public $name = 'Unknown Method Exception'; + public function getName() + { + return \Yii::t('yii', 'Unknown Method'); + } } diff --git a/framework/base/UnknownPropertyException.php b/framework/base/UnknownPropertyException.php index 601ae28..de8de1c 100644 --- a/framework/base/UnknownPropertyException.php +++ b/framework/base/UnknownPropertyException.php @@ -18,8 +18,11 @@ namespace yii\base; class UnknownPropertyException extends \Exception { /** - * @var string the user-friend name of this exception + * @return string the user-friendly name of this exception */ - public $name = 'Unknown Property Exception'; + public function getName() + { + return \Yii::t('yii', 'Unknown Property'); + } } diff --git a/framework/console/Application.php b/framework/console/Application.php index 64c17e5..237be05 100644 --- a/framework/console/Application.php +++ b/framework/console/Application.php @@ -112,7 +112,7 @@ class Application extends \yii\base\Application try { return parent::runAction($route, $params); } catch (InvalidRouteException $e) { - echo "\nError: unknown command \"$route\".\n"; + echo "Error: unknown command \"$route\".\n"; return 1; } } diff --git a/framework/db/Exception.php b/framework/db/Exception.php index 61a8e58..209dc40 100644 --- a/framework/db/Exception.php +++ b/framework/db/Exception.php @@ -18,11 +18,6 @@ namespace yii\db; class Exception extends \yii\base\Exception { /** - * @var string the user-friend name of this exception - */ - public $name = 'Database Exception'; - - /** * @var mixed the error info provided by a PDO exception. This is the same as returned * by [PDO::errorInfo](http://www.php.net/manual/en/pdo.errorinfo.php). */ @@ -39,4 +34,12 @@ class Exception extends \yii\base\Exception $this->errorInfo = $errorInfo; parent::__construct($message, $code); } + + /** + * @return string the user-friendly name of this exception + */ + public function getName() + { + return \Yii::t('yii', 'Database Exception'); + } } \ No newline at end of file From a39638515fe67fd27087a8a14f1266cf4c535e17 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Fri, 1 Feb 2013 08:42:43 -0500 Subject: [PATCH 14/14] Added Command::batchInsert() --- framework/db/Command.php | 29 +++++++++++++++++++++++++++-- framework/db/QueryBuilder.php | 27 +++++++++++++++++++++++++++ framework/db/mysql/QueryBuilder.php | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/framework/db/Command.php b/framework/db/Command.php index 0fb099a..3531fa7 100644 --- a/framework/db/Command.php +++ b/framework/db/Command.php @@ -485,16 +485,41 @@ class Command extends \yii\base\Component * * @param string $table the table that new rows will be inserted into. * @param array $columns the column data (name=>value) to be inserted into the table. - * @param array $params the parameters to be bound to the command * @return Command the command object itself */ - public function insert($table, $columns, $params = array()) + public function insert($table, $columns) { + $params = array(); $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params); return $this->setSql($sql)->bindValues($params); } /** + * Creates a batch INSERT command. + * For example, + * + * ~~~ + * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( + * array('Tom', 30), + * array('Jane', 20), + * array('Linda', 25), + * ))->execute(); + * ~~~ + * + * Not that the values in each row must match the corresponding column names. + * + * @param string $table the table that new rows will be inserted into. + * @param array $columns the column names + * @param array $rows the rows to be batch inserted into the table + * @return Command the command object itself + */ + public function batchInsert($table, $columns, $rows) + { + $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows); + return $this->setSql($sql); + } + + /** * Creates an UPDATE command. * For example, * diff --git a/framework/db/QueryBuilder.php b/framework/db/QueryBuilder.php index d40da91..35bfcb3 100644 --- a/framework/db/QueryBuilder.php +++ b/framework/db/QueryBuilder.php @@ -115,6 +115,33 @@ class QueryBuilder extends \yii\base\Object } /** + * Generates a batch INSERT SQL statement. + * For example, + * + * ~~~ + * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( + * array('Tom', 30), + * array('Jane', 20), + * array('Linda', 25), + * ))->execute(); + * ~~~ + * + * Not that the values in each row must match the corresponding column names. + * + * @param string $table the table that new rows will be inserted into. + * @param array $columns the column names + * @param array $rows the rows to be batch inserted into the table + * @param array $params the parameters to be bound to the command + * @return string the batch INSERT SQL statement + * @throws NotSupportedException if this is not supported by the underlying DBMS + */ + public function batchInsert($table, $columns, $rows, $params = array()) + { + throw new NotSupportedException($this->db->getDriverName() . ' does not support batch insert.'); + + } + + /** * Creates an UPDATE SQL statement. * For example, * diff --git a/framework/db/mysql/QueryBuilder.php b/framework/db/mysql/QueryBuilder.php index 73986af..6168409 100644 --- a/framework/db/mysql/QueryBuilder.php +++ b/framework/db/mysql/QueryBuilder.php @@ -129,4 +129,39 @@ class QueryBuilder extends \yii\db\QueryBuilder { return 'SET FOREIGN_KEY_CHECKS=' . ($check ? 1 : 0); } + + /** + * Generates a batch INSERT SQL statement. + * For example, + * + * ~~~ + * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( + * array('Tom', 30), + * array('Jane', 20), + * array('Linda', 25), + * ))->execute(); + * ~~~ + * + * Not that the values in each row must match the corresponding column names. + * + * @param string $table the table that new rows will be inserted into. + * @param array $columns the column names + * @param array $rows the rows to be batch inserted into the table + * @return string the batch INSERT SQL statement + */ + public function batchInsert($table, $columns, $rows) + { + $values = array(); + foreach ($rows as $row) { + $vs = array(); + foreach ($row as $value) { + $vs[] = is_string($value) ? $this->db->quoteValue($value) : $value; + } + $values[] = $vs; + } + + return 'INSERT INTO ' . $this->db->quoteTableName($table) + . ' (' . implode(', ', $columns) . ') VALUES (' + . implode(', ', $values) . ')'; + } }