Commit 5855b7c1 by Qiang Xue

Merge branch 'master' of git.yiisoft.com:yii2

parents 7ff5d025 3fa22483
...@@ -3,15 +3,15 @@ its parent class [[Object]]. ...@@ -3,15 +3,15 @@ its parent class [[Object]].
Event is a way to "inject" custom code into existing code at certain places. For example, a comment object can trigger Event is a way to "inject" custom code into existing code at certain places. For example, a comment object can trigger
an "add" event when the user adds a comment. We can write custom code and attach it to this event so that when the event an "add" event when the user adds a comment. We can write custom code and attach it to this event so that when the event
is triggered, our custom code will be executed. is triggered (i.e. comment will be added), our custom code will be executed.
An event is identified by a name (unique within the class it is defined). Event names are *case-sensitive*. An event is identified by a name that should be unique within the class it is defined at. Event names are *case-sensitive*.
An event can be attached with one or multiple PHP callbacks, called *event handlers*. One can call [[trigger()]] to One or multiple PHP callbacks, called *event handlers*, could be attached to event. You can call [[trigger()]] to
raise an event. When an event is raised, the attached event handlers will be invoked automatically in the order they are raise an event. When an event is raised, the event handlers will be invoked automatically in the order they were
attached to the event. attached.
To attach an event handler to an event, call [[on()]]. For example, To attach an event handler to an event, call [[on()]]:
~~~ ~~~
$comment->on('add', function($event) { $comment->on('add', function($event) {
...@@ -19,7 +19,8 @@ $comment->on('add', function($event) { ...@@ -19,7 +19,8 @@ $comment->on('add', function($event) {
}); });
~~~ ~~~
In the above, we attach an anonymous function to the "add" event of the comment. Valid event handlers include: In the above, we attach an anonymous function to the "add" event of the comment.
Valid event handlers include:
- anonymous function: `function($event) { ... }` - anonymous function: `function($event) { ... }`
- object method: `array($object, 'handleAdd')` - object method: `array($object, 'handleAdd')`
...@@ -34,7 +35,7 @@ function foo($event) ...@@ -34,7 +35,7 @@ function foo($event)
where `$event` is an [[Event]] object which includes parameters associated with the event. where `$event` is an [[Event]] object which includes parameters associated with the event.
One can also attach an event handler to an event when configuring a component with a configuration array. The syntax is You can also attach an event handler to an event when configuring a component with a configuration array. The syntax is
like the following: like the following:
~~~ ~~~
...@@ -45,7 +46,7 @@ array( ...@@ -45,7 +46,7 @@ array(
where `on add` stands for attaching an event to the `add` event. where `on add` stands for attaching an event to the `add` event.
One can call [[getEventHandlers()]] to retrieve all event handlers that are attached to a specified event. Because this You can call [[getEventHandlers()]] to retrieve all event handlers that are attached to a specified event. Because this
method returns a [[Vector]] object, we can manipulate this object to attach/detach event handlers, or adjust their method returns a [[Vector]] object, we can manipulate this object to attach/detach event handlers, or adjust their
relative orders. relative orders.
......
...@@ -121,8 +121,8 @@ class YiiBase ...@@ -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): * 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; * - `@application/components/GoogleMap`: importing the `GoogleMap` class with a path alias;
* - `@app/components/*`: importing the whole `components` directory 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 * - `GoogleMap`: importing the `GoogleMap` class with a class name. [[autoload()]] will be used
* when this class is used for the first time. * when this class is used for the first time.
* *
...@@ -322,12 +322,12 @@ class YiiBase ...@@ -322,12 +322,12 @@ class YiiBase
* the class. For example, * the class. For example,
* *
* - `\app\components\GoogleMap`: fully-qualified namespaced class. * - `\app\components\GoogleMap`: fully-qualified namespaced class.
* - `@app/components/GoogleMap`: an alias * - `@application/components/GoogleMap`: an alias
* *
* Below are some usage examples: * Below are some usage examples:
* *
* ~~~ * ~~~
* $object = \Yii::createObject('@app/components/GoogleMap'); * $object = \Yii::createObject('@application/components/GoogleMap');
* $object = \Yii::createObject(array( * $object = \Yii::createObject(array(
* 'class' => '\app\components\GoogleMap', * 'class' => '\app\components\GoogleMap',
* 'apiKey' => 'xyz', * 'apiKey' => 'xyz',
......
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
namespace yii\base; namespace yii\base;
use Yii;
use yii\util\FileHelper;
use yii\base\InvalidCallException; use yii\base\InvalidCallException;
/** /**
...@@ -35,7 +37,7 @@ use yii\base\InvalidCallException; ...@@ -35,7 +37,7 @@ use yii\base\InvalidCallException;
* Yii framework messages. This application component is dynamically loaded when needed.</li> * Yii framework messages. This application component is dynamically loaded when needed.</li>
* </ul> * </ul>
* *
* Application will undergo the following lifecycles when processing a user request: * Application will undergo the following life cycles when processing a user request:
* <ol> * <ol>
* <li>load application configuration;</li> * <li>load application configuration;</li>
* <li>set up class autoloader and error handling;</li> * <li>set up class autoloader and error handling;</li>
...@@ -48,28 +50,6 @@ use yii\base\InvalidCallException; ...@@ -48,28 +50,6 @@ use yii\base\InvalidCallException;
* Starting from lifecycle 3, if a PHP error or an uncaught exception occurs, * 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. * 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 <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
...@@ -127,12 +107,12 @@ class Application extends Module ...@@ -127,12 +107,12 @@ class Application extends Module
*/ */
public function __construct($id, $basePath, $config = array()) public function __construct($id, $basePath, $config = array())
{ {
\Yii::$application = $this; Yii::$application = $this;
$this->id = $id; $this->id = $id;
$this->setBasePath($basePath); $this->setBasePath($basePath);
$this->registerDefaultAliases(); $this->registerDefaultAliases();
$this->registerCoreComponents(); $this->registerCoreComponents();
parent::__construct($id, $this, $config); Component::__construct($config);
} }
/** /**
...@@ -202,28 +182,6 @@ class Application extends Module ...@@ -202,28 +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 BadRequestException if the route cannot be resolved into a controller
*/
public function runController($route, $params = array())
{
$result = $this->createController($route);
if ($result === false) {
throw new BadRequestException(\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 = $priorController;
return $status;
}
/**
* Returns the directory that stores runtime files. * Returns the directory that stores runtime files.
* @return string the directory that stores runtime files. Defaults to 'protected/runtime'. * @return string the directory that stores runtime files. Defaults to 'protected/runtime'.
*/ */
...@@ -238,15 +196,15 @@ class Application extends Module ...@@ -238,15 +196,15 @@ class Application extends Module
/** /**
* Sets the directory that stores runtime files. * Sets the directory that stores runtime files.
* @param string $path 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) public function setRuntimePath($path)
{ {
$p = \Yii::getAlias($path); $p = FileHelper::ensureDirectory($path);
if ($p === false || !is_dir($p) || !is_writable($path)) { if (is_writable($p)) {
throw new InvalidCallException("Application runtime path \"$path\" is invalid. Please make sure it is a directory writable by the Web server process.");
} else {
$this->_runtimePath = $p; $this->_runtimePath = $p;
} else {
throw new InvalidConfigException("Runtime path must be writable by the Web server process: $path");
} }
} }
...@@ -295,34 +253,61 @@ class Application extends Module ...@@ -295,34 +253,61 @@ class Application extends Module
date_default_timezone_set($value); date_default_timezone_set($value);
} }
/** // /**
* Returns the locale instance. // * Returns the security manager component.
* @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used. // * @return SecurityManager the security manager application component.
* @return CLocale the locale instance // */
*/ // public function getSecurityManager()
public function getLocale($localeID = null) // {
{ // return $this->getComponent('securityManager');
return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID); // }
} //
// /**
/** // * Returns the locale instance.
* @return CNumberFormatter the locale-dependent number formatter. // * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
* The current {@link getLocale application locale} will be used. // * @return CLocale the locale instance
*/ // */
public function getNumberFormatter() // public function getLocale($localeID = null)
{ // {
return $this->getLocale()->getNumberFormatter(); // return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID);
} // }
//
/** // /**
* Returns the locale-dependent date formatter. // * @return CNumberFormatter the locale-dependent number formatter.
* @return CDateFormatter the locale-dependent date formatter. // * The current {@link getLocale application locale} will be used.
* The current {@link getLocale application locale} will be used. // */
*/ // public function getNumberFormatter()
public function getDateFormatter() // {
{ // return $this->getLocale()->getNumberFormatter();
return $this->getLocale()->getDateFormatter(); // }
} //
// /**
// * 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. * Returns the database connection component.
...@@ -352,15 +337,6 @@ class Application extends Module ...@@ -352,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. * Returns the cache component.
* @return \yii\caching\Cache the cache application component. Null if the component is not enabled. * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
*/ */
...@@ -370,24 +346,6 @@ class Application extends Module ...@@ -370,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. * Returns the request component.
* @return Request the request component * @return Request the request component
*/ */
...@@ -401,9 +359,9 @@ class Application extends Module ...@@ -401,9 +359,9 @@ class Application extends Module
*/ */
public function registerDefaultAliases() public function registerDefaultAliases()
{ {
\Yii::$aliases['@application'] = $this->getBasePath(); Yii::$aliases['@application'] = $this->getBasePath();
\Yii::$aliases['@entry'] = dirname($_SERVER['SCRIPT_FILENAME']); Yii::$aliases['@entry'] = dirname($_SERVER['SCRIPT_FILENAME']);
\Yii::$aliases['@www'] = ''; Yii::$aliases['@www'] = '';
} }
/** /**
...@@ -416,15 +374,6 @@ class Application extends Module ...@@ -416,15 +374,6 @@ class Application extends Module
'errorHandler' => array( 'errorHandler' => array(
'class' => 'yii\base\ErrorHandler', 'class' => 'yii\base\ErrorHandler',
), ),
'request' => array(
'class' => 'yii\base\Request',
),
'response' => array(
'class' => 'yii\base\Response',
),
'format' => array(
'class' => 'yii\base\Formatter',
),
'coreMessages' => array( 'coreMessages' => array(
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'language' => 'en_us', 'language' => 'en_us',
......
<?php
/**
* InvalidRequestException class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* InvalidRequestException represents an exception caused by incorrect end user request.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class InvalidRequestException extends \Exception
{
}
<?php <?php
/** /**
* BadRequestException class file. * InvalidRouteException class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright &copy; 2008 Yii Software LLC
...@@ -10,12 +10,12 @@ ...@@ -10,12 +10,12 @@
namespace yii\base; namespace yii\base;
/** /**
* BadRequestException represents an exception caused by incorrect end user request. * InvalidRouteException represents an exception caused by an invalid route.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class BadRequestException extends \Exception class InvalidRouteException extends \Exception
{ {
} }
...@@ -97,7 +97,7 @@ class View extends Component ...@@ -97,7 +97,7 @@ class View extends Component
* To determine which view file should be rendered, the method calls [[findViewFile()]] which * To determine which view file should be rendered, the method calls [[findViewFile()]] which
* will search in the directories as specified by [[basePath]]. * 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 * or a path relative to [[basePath]]. The file suffix is optional and defaults to `.php` if not given
* in the view name. * in the view name.
* *
......
...@@ -80,7 +80,7 @@ class Widget extends Component ...@@ -80,7 +80,7 @@ class Widget extends Component
* To determine which view file should be rendered, the method calls [[findViewFile()]] which * To determine which view file should be rendered, the method calls [[findViewFile()]] which
* will search in the directories as specified by [[basePath]]. * 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 * or a path relative to [[basePath]]. The file suffix is optional and defaults to `.php` if not given
* in the view name. * in the view name.
* *
......
...@@ -70,14 +70,14 @@ class Application extends \yii\base\Application ...@@ -70,14 +70,14 @@ class Application extends \yii\base\Application
parent::init(); parent::init();
if ($this->enableCoreCommands) { if ($this->enableCoreCommands) {
foreach ($this->coreCommands() as $id => $command) { foreach ($this->coreCommands() as $id => $command) {
if (!isset($this->controllers[$id])) { if (!isset($this->controllerMap[$id])) {
$this->controllers[$id] = $command; $this->controllerMap[$id] = $command;
} }
} }
} }
// ensure we have the 'help' command so that we can list the available commands // ensure we have the 'help' command so that we can list the available commands
if (!isset($this->controllers['help'])) { if (!isset($this->controllerMap['help'])) {
$this->controllers['help'] = 'yii\console\controllers\HelpController'; $this->controllerMap['help'] = 'yii\console\controllers\HelpController';
} }
} }
......
...@@ -87,7 +87,7 @@ class HelpController extends Controller ...@@ -87,7 +87,7 @@ class HelpController extends Controller
*/ */
public function getActions($controller) public function getActions($controller)
{ {
$actions = array_keys($controller->actions); $actions = array_keys($controller->actionMap);
$class = new \ReflectionClass($controller); $class = new \ReflectionClass($controller);
foreach ($class->getMethods() as $method) { foreach ($class->getMethods() as $method) {
/** @var $method \ReflectionMethod */ /** @var $method \ReflectionMethod */
...@@ -114,7 +114,7 @@ class HelpController extends Controller ...@@ -114,7 +114,7 @@ class HelpController extends Controller
} }
$commands = array(); $commands = array();
foreach (array_keys($module->controllers) as $id) { foreach (array_keys($module->controllerMap) as $id) {
$commands[] = $prefix . $id; $commands[] = $prefix . $id;
} }
......
...@@ -89,16 +89,17 @@ class DbTarget extends Target ...@@ -89,16 +89,17 @@ class DbTarget extends Target
} }
/** /**
* Stores log [[messages]] to DB. * Stores log messages to DB.
* @param boolean $final whether this method is called at the end of the current application * @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(); $db = $this->getDb();
$tableName = $db->quoteTableName($this->tableName); $tableName = $db->quoteTableName($this->tableName);
$sql = "INSERT INTO $tableName (level, category, log_time, message) VALUES (:level, :category, :log_time, :message)"; $sql = "INSERT INTO $tableName (level, category, log_time, message) VALUES (:level, :category, :log_time, :message)";
$command = $db->createCommand($sql); $command = $db->createCommand($sql);
foreach ($this->messages as $message) { foreach ($messages as $message) {
$command->bindValues(array( $command->bindValues(array(
':level' => $message[1], ':level' => $message[1],
':category' => $message[2], ':category' => $message[2],
......
...@@ -39,13 +39,14 @@ class EmailTarget extends Target ...@@ -39,13 +39,14 @@ class EmailTarget extends Target
public $headers = array(); public $headers = array();
/** /**
* Sends log [[messages]] to specified email addresses. * Sends log messages to specified email addresses.
* @param boolean $final whether this method is called at the end of the current application * @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 = ''; $body = '';
foreach ($this->messages as $message) { foreach ($messages as $message) {
$body .= $this->formatMessage($message); $body .= $this->formatMessage($message);
} }
$body = wordwrap($body, 70); $body = wordwrap($body, 70);
......
...@@ -65,19 +65,28 @@ class FileTarget extends Target ...@@ -65,19 +65,28 @@ class FileTarget extends Target
} }
/** /**
* Sends log [[messages]] to specified email addresses. * Sends log messages to specified email addresses.
* @param boolean $final whether this method is called at the end of the current application * @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) { if (@filesize($this->logFile) > $this->maxFileSize * 1024) {
$this->rotateFiles(); $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);
} }
/** /**
......
...@@ -8,16 +8,13 @@ ...@@ -8,16 +8,13 @@
*/ */
namespace yii\logging; namespace yii\logging;
use yii\base\InvalidConfigException;
use yii\base\Event;
use yii\base\Exception;
/** /**
* Logger records logged messages in memory. * Logger records logged messages in memory.
* *
* When [[flushInterval()]] is reached or when application terminates, it will * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]]
* call [[flush()]] to send logged messages to different log targets, such as * to send logged messages to different log targets, such as file, email, Web.
* file, email, Web.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -25,15 +22,6 @@ use yii\base\Exception; ...@@ -25,15 +22,6 @@ use yii\base\Exception;
class Logger extends \yii\base\Component 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 * Error message level. An error message is one that indicates the abnormal termination of the
* application and may require developer's handling. * application and may require developer's handling.
*/ */
...@@ -82,7 +70,7 @@ class Logger extends \yii\base\Component ...@@ -82,7 +70,7 @@ class Logger extends \yii\base\Component
* *
* ~~~ * ~~~
* array( * array(
* [0] => message (mixed) * [0] => message (mixed, can be a string or some complex data, such as an exception object)
* [1] => level (integer) * [1] => level (integer)
* [2] => category (string) * [2] => category (string)
* [3] => timestamp (float, obtained by microtime(true)) * [3] => timestamp (float, obtained by microtime(true))
...@@ -90,6 +78,10 @@ class Logger extends \yii\base\Component ...@@ -90,6 +78,10 @@ class Logger extends \yii\base\Component
* ~~~ * ~~~
*/ */
public $messages = array(); 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. * Initializes the logger by registering [[flush()]] as a shutdown function.
...@@ -138,7 +130,9 @@ class Logger extends \yii\base\Component ...@@ -138,7 +130,9 @@ class Logger extends \yii\base\Component
*/ */
public function flush($final = false) 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(); $this->messages = array();
} }
...@@ -149,7 +143,7 @@ class Logger extends \yii\base\Component ...@@ -149,7 +143,7 @@ class Logger extends \yii\base\Component
* of [[YiiBase]] class file. * of [[YiiBase]] class file.
* @return float the total elapsed time in seconds for current request. * @return float the total elapsed time in seconds for current request.
*/ */
public function getExecutionTime() public function getElapsedTime()
{ {
return microtime(true) - YII_BEGIN_TIME; return microtime(true) - YII_BEGIN_TIME;
} }
...@@ -218,7 +212,7 @@ class Logger extends \yii\base\Component ...@@ -218,7 +212,7 @@ class Logger extends \yii\base\Component
if (($last = array_pop($stack)) !== null && $last[0] === $token) { if (($last = array_pop($stack)) !== null && $last[0] === $token) {
$timings[] = array($token, $category, $timestamp - $last[3]); $timings[] = array($token, $category, $timestamp - $last[3]);
} else { } 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 ...@@ -231,5 +225,4 @@ class Logger extends \yii\base\Component
return $timings; return $timings;
} }
} }
...@@ -81,26 +81,21 @@ class Router extends Component ...@@ -81,26 +81,21 @@ class Router extends Component
$this->targets[$name] = Yii::createObject($target); $this->targets[$name] = Yii::createObject($target);
} }
} }
Yii::getLogger()->router = $this;
Yii::getLogger()->on(Logger::EVENT_FLUSH, array($this, 'processMessages'));
Yii::getLogger()->on(Logger::EVENT_FINAL_FLUSH, array($this, 'processMessages'));
} }
/** /**
* Retrieves and processes log messages from the system logger. * Dispatches log messages to [[targets]].
* This method mainly serves the event handler to the [[Logger::EVENT_FLUSH]] event * This method is called by [[Logger]] when its [[Logger::flush()]] method is called.
* and the [[Logger::EVENT_FINAL_FLUSH]] event. * It will forward the messages to each log target registered in [[targets]].
* It will retrieve the available log messages from the [[Yii::getLogger()|system logger]] * @param array $messages the messages to be processed
* and invoke the registered [[targets|log targets]] to do the actual processing. * @param boolean $final whether this is the final call during a request cycle
* @param \yii\base\Event $event event parameter
*/ */
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) { foreach ($this->targets as $target) {
if ($target->enabled) { if ($target->enabled) {
$target->processMessages($messages, $final); $target->collect($messages, $final);
} }
} }
} }
......
...@@ -50,15 +50,6 @@ abstract class Target extends \yii\base\Component ...@@ -50,15 +50,6 @@ abstract class Target extends \yii\base\Component
*/ */
public $except = array(); 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. * @var boolean whether to log a message containing the current user name and ID. Defaults to false.
* @see \yii\web\User * @see \yii\web\User
*/ */
...@@ -77,19 +68,18 @@ abstract class Target extends \yii\base\Component ...@@ -77,19 +68,18 @@ abstract class Target extends \yii\base\Component
public $exportInterval = 1000; public $exportInterval = 1000;
/** /**
* @var array the messages that are retrieved from the logger so far by this log target. * @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; private $_levels = 0;
/** /**
* Exports log messages to a specific destination. * Exports log messages to a specific destination.
* Child classes must implement this method. Note that you may need * Child classes must implement this method.
* to clean up [[messages]] in this method to avoid re-exporting messages. * @param array $messages the messages to be exported. See [[Logger::messages]] for the structure
* @param boolean $final whether this method is called at the end of the current application * of each message.
*/ */
abstract public function exportMessages($final); abstract public function export($messages);
/** /**
* Processes the given log messages. * Processes the given log messages.
...@@ -99,45 +89,16 @@ abstract class Target extends \yii\base\Component ...@@ -99,45 +89,16 @@ abstract class Target extends \yii\base\Component
* of each message. * of each message.
* @param boolean $final whether this method is called at the end of the current application * @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($this->_messages, $this->filterMessages($messages));
$this->messages = array_merge($this->messages, $messages); $count = count($this->_messages);
$count = count($this->messages);
if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) { if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
$this->prepareExport($final); if (($context = $this->getContextMessage()) !== '') {
$this->exportMessages($final); $this->_messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME);
$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 ($final && ($context = $this->getContextMessage()) !== '') { $this->export($this->_messages);
$this->messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME); $this->_messages = array();
} }
} }
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
namespace yii\util; namespace yii\util;
use yii\base\Exception; use yii\base\Exception;
use yii\base\InvalidConfigException;
/** /**
* Filesystem helper * Filesystem helper
...@@ -37,7 +38,7 @@ class FileHelper ...@@ -37,7 +38,7 @@ class FileHelper
* If the given path does not refer to an existing directory, an exception will be thrown. * 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. * @param string $path the given path. This can also be a path alias.
* @return string the normalized path * @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) public static function ensureDirectory($path)
{ {
...@@ -45,7 +46,7 @@ class FileHelper ...@@ -45,7 +46,7 @@ class FileHelper
if ($p !== false && ($p = realpath($p)) !== false && is_dir($p)) { if ($p !== false && ($p = realpath($p)) !== false && is_dir($p)) {
return $p; return $p;
} else { } else {
throw new Exception('Directory does not exist: ' . $path); throw new InvalidConfigException('Directory does not exist: ' . $path);
} }
} }
......
...@@ -84,4 +84,17 @@ class StringHelper ...@@ -84,4 +84,17 @@ class StringHelper
return trim(strtolower(str_replace('_', $separator, preg_replace('/(?<![A-Z])[A-Z]/', $separator . '\0', $name))), $separator); return trim(strtolower(str_replace('_', $separator, preg_replace('/(?<![A-Z])[A-Z]/', $separator . '\0', $name))), $separator);
} }
} }
/**
* Converts an ID into a CamelCase name.
* Words in the ID separated by `$separator` (defaults to '-') will be concatenated into a CamelCase name.
* For example, 'post-tag' is converted to 'PostTag'.
* @param string $id the ID to be converted
* @param string $separator the character used to separate the words in the ID
* @return string the resulting CamelCase name
*/
public static function id2camel($id, $separator = '-')
{
return str_replace(' ', '', ucwords(implode(' ', explode($separator, $id))));
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment