Browse Source

working on error handler.

tags/2.0.0-beta
Qiang Xue 13 years ago
parent
commit
e585c69fbb
  1. 8
      framework/YiiBase.php
  2. 121
      framework/base/Application.php
  3. 462
      framework/base/ErrorHandler.php
  4. 74
      framework/base/StatePersister.php
  5. 27
      framework/base/View.php
  6. 11
      framework/db/ar/ActiveQuery.php
  7. 10
      framework/db/ar/ActiveRecord.php
  8. 16
      framework/logging/Logger.php
  9. 17
      framework/logging/Router.php
  10. 40
      framework/web/HttpException.php

8
framework/YiiBase.php

@ -22,14 +22,6 @@ defined('YII_DEBUG') or define('YII_DEBUG', false);
*/ */
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 0); defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 0);
/** /**
* This constant defines whether exception handling should be enabled. Defaults to true.
*/
defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER', true);
/**
* This constant defines whether error handling should be enabled. Defaults to true.
*/
defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true);
/**
* This constant defines the framework installation directory. * This constant defines the framework installation directory.
*/ */
defined('YII_PATH') or define('YII_PATH', __DIR__); defined('YII_PATH') or define('YII_PATH', __DIR__);

121
framework/base/Application.php

@ -91,8 +91,6 @@ abstract class Application extends Module
public $sourceLanguage = 'en_us'; public $sourceLanguage = 'en_us';
private $_runtimePath; private $_runtimePath;
private $_globalState;
private $_stateChanged;
private $_ended = false; private $_ended = false;
private $_language; private $_language;
@ -417,95 +415,6 @@ abstract class Application extends Module
} }
/** /**
* Returns a global value.
*
* A global value is one that is persistent across users sessions and requests.
* @param string $key the name of the value to be returned
* @param mixed $defaultValue the default value. If the named global value is not found, this will be returned instead.
* @return mixed the named global value
* @see setGlobalState
*/
public function getGlobalState($key, $defaultValue = null)
{
if ($this->_globalState === null) {
$this->loadGlobalState();
}
return isset($this->_globalState[$key]) ? $this->_globalState[$key] : $defaultValue;
}
/**
* Sets a global value.
*
* A global value is one that is persistent across users sessions and requests.
* Make sure that the value is serializable and unserializable.
* @param string $key the name of the value to be saved
* @param mixed $value the global value to be saved. It must be serializable.
* @param mixed $defaultValue the default value. If the named global value is the same as this value, it will be cleared from the current storage.
* @see getGlobalState
*/
public function setGlobalState($key, $value, $defaultValue = null)
{
if ($this->_globalState === null) {
$this->loadGlobalState();
}
$changed = $this->_stateChanged;
if ($value === $defaultValue) {
if (isset($this->_globalState[$key])) {
unset($this->_globalState[$key]);
$this->_stateChanged = true;
}
} elseif (!isset($this->_globalState[$key]) || $this->_globalState[$key] !== $value) {
$this->_globalState[$key] = $value;
$this->_stateChanged = true;
}
if ($this->_stateChanged !== $changed) {
$this->on('afterRequest', array($this, 'saveGlobalState'));
}
}
/**
* Clears a global value.
*
* The value cleared will no longer be available in this request and the following requests.
* @param string $key the name of the value to be cleared
*/
public function clearGlobalState($key)
{
$this->setGlobalState($key, null);
}
/**
* Loads the global state data from persistent storage.
* @see getStatePersister
* @throws \yii\base\Exception if the state persister is not available
*/
public function loadGlobalState()
{
$persister = $this->getStatePersister();
if (($this->_globalState = $persister->load()) === null) {
$this->_globalState = array();
}
$this->_stateChanged = false;
$this->off('afterRequest', array($this, 'saveGlobalState'));
}
/**
* Saves the global state data into persistent storage.
* @see getStatePersister
* @throws \yii\base\Exception if the state persister is not available
*/
public function saveGlobalState()
{
if ($this->_stateChanged) {
$this->_stateChanged = false;
$this->off('afterRequest', array($this, 'saveGlobalState'));
$this->getStatePersister()->save($this->_globalState);
}
}
/**
* Handles uncaught PHP exceptions. * Handles uncaught PHP exceptions.
* *
* This method is implemented as a PHP exception handler. It requires * This method is implemented as a PHP exception handler. It requires
@ -666,36 +575,6 @@ abstract class Application extends Module
} }
/** /**
* Raised when an uncaught PHP exception occurs.
*
* An event handler can set the {@link ExceptionEvent::handled handled}
* property of the event parameter to be true to indicate no further error
* handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
* application component will continue processing the error.
*
* @param ExceptionEvent $event event parameter
*/
public function onException($event)
{
$this->trigger('exception', $event);
}
/**
* Raised when a PHP execution error occurs.
*
* An event handler can set the {@link ErrorEvent::handled handled}
* property of the event parameter to be true to indicate no further error
* handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
* application component will continue processing the error.
*
* @param ErrorEvent $event event parameter
*/
public function onError($event)
{
$this->trigger('error', $event);
}
/**
* Displays the captured PHP error. * Displays the captured PHP error.
* This method displays the error in HTML when there is * This method displays the error in HTML when there is
* no active error handler. * no active error handler.

462
framework/base/ErrorHandler.php

@ -1,23 +1,22 @@
<?php <?php
/** /**
* This file contains the error handler application component. * ErrorHandler class file.
* *
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
Yii::import('CHtml',true); namespace yii\base;
/** /**
* CErrorHandler handles uncaught PHP errors and exceptions. * ErrorHandler handles uncaught PHP errors and exceptions.
* *
* It displays these errors using appropriate views based on the * It displays these errors using appropriate views based on the
* nature of the error and the mode the application runs at. * nature of the error and the mode the application runs at.
* It also chooses the most preferred language for displaying the error. * It also chooses the most preferred language for displaying the error.
* *
* CErrorHandler uses two sets of views: * ErrorHandler uses two sets of views:
* <ul> * <ul>
* <li>development views, named as <code>exception.php</code>; * <li>development views, named as <code>exception.php</code>;
* <li>production views, named as <code>error&lt;StatusCode&gt;.php</code>; * <li>production views, named as <code>error&lt;StatusCode&gt;.php</code>;
@ -33,7 +32,7 @@ Yii::import('CHtml',true);
* For security reasons, they only display the error message without any * For security reasons, they only display the error message without any
* sensitive information. * sensitive information.
* *
* CErrorHandler looks for the view templates from the following locations in order: * ErrorHandler looks for the view templates from the following locations in order:
* <ol> * <ol>
* <li><code>themes/ThemeName/views/system</code>: when a theme is active.</li> * <li><code>themes/ThemeName/views/system</code>: when a theme is active.</li>
* <li><code>protected/views/system</code></li> * <li><code>protected/views/system</code></li>
@ -44,70 +43,151 @@ Yii::import('CHtml',true);
* The property {@link maxSourceLines} can be changed to specify the number * The property {@link maxSourceLines} can be changed to specify the number
* of source code lines to be displayed in development views. * of source code lines to be displayed in development views.
* *
* CErrorHandler is a core application component that can be accessed via * ErrorHandler is a core application component that can be accessed via
* {@link CApplication::getErrorHandler()}. * {@link CApplication::getErrorHandler()}.
* *
* @property array $error The error details. Null if there is no error. * @property array $error The error details. Null if there is no error.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id$ * @since 2.0
* @package system.base
* @since 1.0
*/ */
class CErrorHandler extends CApplicationComponent class ErrorHandler extends ApplicationComponent
{ {
/** /**
* @var integer maximum number of source code lines to be displayed. Defaults to 25. * @var integer maximum number of source code lines to be displayed. Defaults to 25.
*/ */
public $maxSourceLines=25; public $maxSourceLines = 25;
/** /**
* @var integer maximum number of trace source code lines to be displayed. Defaults to 10. * @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
* @since 1.1.6
*/ */
public $maxTraceSourceLines = 10; public $maxTraceSourceLines = 10;
/** /**
* @var string the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'. * @var string the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'.
*/ */
public $adminInfo='the webmaster'; public $adminInfo = 'the webmaster';
/** /**
* @var boolean whether to discard any existing page output before error display. Defaults to true. * @var boolean whether to discard any existing page output before error display. Defaults to true.
*/ */
public $discardOutput=true; public $discardExistingOutput = true;
/** /**
* @var string the route (eg 'site/error') to the controller action that will be used to display external errors. * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
* Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error. * Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error.
* This property defaults to null, meaning CErrorHandler will handle the error display. * This property defaults to null, meaning ErrorHandler will handle the error display.
*/ */
public $errorAction; public $errorAction;
private $_error; private $_error;
public $exception;
public $compactOutput;
public function init()
{
set_exception_handler(array($this, 'handleException'));
set_error_handler(array($this, 'handleError'), error_reporting());
}
protected function logException($exception)
{
$category = get_class($exception);
if ($exception instanceof HttpException) {
$category .= '\\' . $exception->statusCode;
} elseif ($exception instanceof \ErrorException) {
$category .= '\\' . $exception->getSeverity();
}
\Yii::error((string)$exception, $category);
}
protected function clearOutput()
{
// the following manual level counting is to deal with zlib.output_compression set to On
for ($level = ob_get_level(); $level > 0; --$level) {
@ob_end_clean();
}
}
protected function simple()
{
if (YII_DEBUG) {
echo '<h1>' . get_class($exception) . "</h1>\n";
echo '<p>' . $exception->getMessage() . ' (' . $exception->getFile() . ':' . $exception->getLine() . ')</p>';
echo '<pre>' . $exception->getTraceAsString() . '</pre>';
} else
{
echo '<h1>' . get_class($exception) . "</h1>\n";
echo '<p>' . $exception->getMessage() . '</p>';
}
}
/** /**
* Handles the exception/error event. * @param \Exception $exception
* This method is invoked by the application whenever it captures
* an exception or PHP error.
* @param CEvent $event the event containing the exception/error information
*/ */
public function handle($event) public function handleException($exception)
{ {
// set event as handled to prevent it from being handled by other event handlers $this->exception = $exception;
$event->handled=true;
if($this->discardOutput) // disable error capturing to avoid recursive errors
{ restore_error_handler();
// the following manual level counting is to deal with zlib.output_compression set to On restore_exception_handler();
for($level=ob_get_level();$level>0;--$level)
{ $this->logException($exception);
@ob_end_clean(); if ($this->discardExistingOutput) {
$this->clearOutput();
}
if ($this->compactOutput === null) {
// not in Web application, or not in AJAX request
$this->compactOutput = !(\Yii::$application instanceof \yii\web\Application) || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}
if ($this->compactOutput) {
$this->simple();
return;
}
if (($trace = $this->getExactTrace($exception)) === null) {
$fileName = $exception->getFile();
$errorLine = $exception->getLine();
} else {
$fileName = $trace['file'];
$errorLine = $trace['line'];
}
$trace = $exception->getTrace();
foreach ($trace as $i => $t) {
if (!isset($t['file'])) {
$trace[$i]['file'] = 'unknown';
}
if (!isset($t['line'])) {
$trace[$i]['line'] = 0;
} }
if (!isset($t['function'])) {
$trace[$i]['function'] = 'unknown';
}
unset($trace[$i]['object']);
}
$this->_error = $data = array(
'code' => $exception instanceof HttpException ? $exception->statusCode : 500,
'type' => get_class($exception),
'errorCode' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $fileName,
'line' => $errorLine,
'trace' => $exception->getTraceAsString(),
'traces' => $trace,
);
if (!headers_sent()) {
header("HTTP/1.0 {$data['code']} " . get_class($exception));
} }
if($event instanceof CExceptionEvent) if ($exception instanceof HttpException || !YII_DEBUG) {
$this->handleException($event->exception); $this->render('error', $data);
else // CErrorEvent } else {
$this->handleError($event); $this->render('exception', $data);
}
} }
/** /**
@ -130,103 +210,38 @@ class CErrorHandler extends CApplicationComponent
} }
/** /**
* Handles the exception.
* @param Exception $exception the exception captured
*/
protected function handleException($exception)
{
$app=Yii::app();
if($app instanceof CWebApplication)
{
if(($trace=$this->getExactTrace($exception))===null)
{
$fileName=$exception->getFile();
$errorLine=$exception->getLine();
}
else
{
$fileName=$trace['file'];
$errorLine=$trace['line'];
}
$trace = $exception->getTrace();
foreach($trace as $i=>$t)
{
if(!isset($t['file']))
$trace[$i]['file']='unknown';
if(!isset($t['line']))
$trace[$i]['line']=0;
if(!isset($t['function']))
$trace[$i]['function']='unknown';
unset($trace[$i]['object']);
}
$this->_error=$data=array(
'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
'type'=>get_class($exception),
'errorCode'=>$exception->getCode(),
'message'=>$exception->getMessage(),
'file'=>$fileName,
'line'=>$errorLine,
'trace'=>$exception->getTraceAsString(),
'traces'=>$trace,
);
if(!headers_sent())
header("HTTP/1.0 {$data['code']} ".get_class($exception));
if($exception instanceof CHttpException || !YII_DEBUG)
$this->render('error',$data);
else
{
if($this->isAjaxRequest())
$app->displayException($exception);
else
$this->render('exception',$data);
}
}
else
$app->displayException($exception);
}
/**
* Handles the PHP error. * Handles the PHP error.
* @param CErrorEvent $event the PHP error event * @param CErrorEvent $event the PHP error event
*/ */
protected function handleError($event) protected function handleError($event)
{ {
$trace=debug_backtrace(); $trace = debug_backtrace();
// skip the first 3 stacks as they do not tell the error position // skip the first 3 stacks as they do not tell the error position
if(count($trace)>3) if (count($trace) > 3)
$trace=array_slice($trace,3); $trace = array_slice($trace, 3);
$traceString=''; $traceString = '';
foreach($trace as $i=>$t) foreach ($trace as $i => $t)
{ {
if(!isset($t['file'])) if (!isset($t['file']))
$trace[$i]['file']='unknown'; $trace[$i]['file'] = 'unknown';
if(!isset($t['line'])) if (!isset($t['line']))
$trace[$i]['line']=0; $trace[$i]['line'] = 0;
if(!isset($t['function'])) if (!isset($t['function']))
$trace[$i]['function']='unknown'; $trace[$i]['function'] = 'unknown';
$traceString.="#$i {$trace[$i]['file']}({$trace[$i]['line']}): "; $traceString .= "#$i {$trace[$i]['file']}({$trace[$i]['line']}): ";
if(isset($t['object']) && is_object($t['object'])) if (isset($t['object']) && is_object($t['object']))
$traceString.=get_class($t['object']).'->'; $traceString .= get_class($t['object']) . '->';
$traceString.="{$trace[$i]['function']}()\n"; $traceString .= "{$trace[$i]['function']}()\n";
unset($trace[$i]['object']); unset($trace[$i]['object']);
} }
$app=Yii::app(); $app = Yii::app();
if($app instanceof CWebApplication) if ($app instanceof CWebApplication) {
{ switch ($event->code)
switch($event->code)
{ {
case E_WARNING: case E_WARNING:
$type = 'PHP warning'; $type = 'PHP warning';
@ -249,51 +264,41 @@ class CErrorHandler extends CApplicationComponent
default: default:
$type = 'PHP error'; $type = 'PHP error';
} }
$this->_error=$data=array( $this->_error = $data = array(
'code'=>500, 'code' => 500,
'type'=>$type, 'type' => $type,
'message'=>$event->message, 'message' => $event->message,
'file'=>$event->file, 'file' => $event->file,
'line'=>$event->line, 'line' => $event->line,
'trace'=>$traceString, 'trace' => $traceString,
'traces'=>$trace, 'traces' => $trace,
); );
if(!headers_sent()) if (!headers_sent())
header("HTTP/1.0 500 PHP Error"); header("HTTP/1.0 500 PHP Error");
if($this->isAjaxRequest()) if ($this->isAjaxRequest())
$app->displayError($event->code,$event->message,$event->file,$event->line); $app->displayError($event->code, $event->message, $event->file, $event->line);
else if(YII_DEBUG) else if (YII_DEBUG)
$this->render('exception',$data); $this->render('exception', $data);
else else
$this->render('error',$data); $this->render('error', $data);
} }
else else
$app->displayError($event->code,$event->message,$event->file,$event->line); $app->displayError($event->code, $event->message, $event->file, $event->line);
}
/**
* whether the current request is an AJAX (XMLHttpRequest) request.
* @return boolean whether the current request is an AJAX request.
*/
protected function isAjaxRequest()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
} }
/** /**
* Returns the exact trace where the problem occurs. * Returns the exact trace where the problem occurs.
* @param Exception $exception the uncaught exception * @param \Exception $exception the uncaught exception
* @return array the exact trace where the problem occurs * @return array the exact trace where the problem occurs
*/ */
protected function getExactTrace($exception) protected function getExactTrace($exception)
{ {
$traces=$exception->getTrace(); $traces = $exception->getTrace();
foreach ($traces as $trace) {
foreach($traces as $trace)
{
// property access exception // property access exception
if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set')) if (isset($trace['function']) && ($trace['function'] === '__get' || $trace['function'] === '__set')) {
return $trace; return $trace;
}
} }
return null; return null;
} }
@ -304,17 +309,17 @@ class CErrorHandler extends CApplicationComponent
* See {@link getViewFile} for how a view file is located given its name. * See {@link getViewFile} for how a view file is located given its name.
* @param array $data data to be passed to the view * @param array $data data to be passed to the view
*/ */
protected function render($view,$data) protected function render($view, $data)
{ {
if($view==='error' && $this->errorAction!==null) if ($view === 'error' && $this->errorAction !== null)
Yii::app()->runController($this->errorAction); Yii::app()->runController($this->errorAction);
else else
{ {
// additional information to be passed to view // additional information to be passed to view
$data['version']=$this->getVersionInfo(); $data['version'] = $this->getVersionInfo();
$data['time']=time(); $data['time'] = time();
$data['admin']=$this->adminInfo; $data['admin'] = $this->adminInfo;
include($this->getViewFile($view,$data['code'])); include($this->getViewFile($view, $data['code']));
} }
} }
@ -324,21 +329,20 @@ class CErrorHandler extends CApplicationComponent
* @param integer $code HTTP status code * @param integer $code HTTP status code
* @return string view file path * @return string view file path
*/ */
protected function getViewFile($view,$code) protected function getViewFile($view, $code)
{ {
$viewPaths=array( $viewPaths = array(
Yii::app()->getTheme()===null ? null : Yii::app()->getTheme()->getSystemViewPath(), Yii::app()->getTheme() === null ? null : Yii::app()->getTheme()->getSystemViewPath(),
Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null, Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null,
YII_PATH.DIRECTORY_SEPARATOR.'views', YII_PATH . DIRECTORY_SEPARATOR . 'views',
); );
foreach($viewPaths as $i=>$viewPath) foreach ($viewPaths as $i => $viewPath)
{ {
if($viewPath!==null) if ($viewPath !== null) {
{ $viewFile = $this->getViewFileInternal($viewPath, $view, $code, $i === 2 ? 'en_us' : null);
$viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null); if (is_file($viewFile))
if(is_file($viewFile)) return $viewFile;
return $viewFile;
} }
} }
} }
@ -351,17 +355,16 @@ class CErrorHandler extends CApplicationComponent
* @param string $srcLanguage the language that the view file is in * @param string $srcLanguage the language that the view file is in
* @return string view file path * @return string view file path
*/ */
protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null) protected function getViewFileInternal($viewPath, $view, $code, $srcLanguage = null)
{ {
$app=Yii::app(); $app = Yii::app();
if($view==='error') if ($view === 'error') {
{ $viewFile = $app->findLocalizedFile($viewPath . DIRECTORY_SEPARATOR . "error{$code}.php", $srcLanguage);
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage); if (!is_file($viewFile))
if(!is_file($viewFile)) $viewFile = $app->findLocalizedFile($viewPath . DIRECTORY_SEPARATOR . 'error.php', $srcLanguage);
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
} }
else else
$viewFile=$viewPath.DIRECTORY_SEPARATOR."exception.php"; $viewFile = $viewPath . DIRECTORY_SEPARATOR . "exception.php";
return $viewFile; return $viewFile;
} }
@ -372,14 +375,14 @@ class CErrorHandler extends CApplicationComponent
*/ */
protected function getVersionInfo() protected function getVersionInfo()
{ {
if(YII_DEBUG) if (YII_DEBUG) {
{ $version = '<a href="http://www.yiiframework.com/">Yii Framework</a>/' . \Yii::getVersion();
$version='<a href="http://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion(); if (isset($_SERVER['SERVER_SOFTWARE'])) {
if(isset($_SERVER['SERVER_SOFTWARE'])) $version = $_SERVER['SERVER_SOFTWARE'] . ' ' . $version;
$version=$_SERVER['SERVER_SOFTWARE'].' '.$version; }
} else {
$version = '';
} }
else
$version='';
return $version; return $version;
} }
@ -391,47 +394,43 @@ class CErrorHandler extends CApplicationComponent
*/ */
protected function argumentsToString($args) protected function argumentsToString($args)
{ {
$count=0; $count = 0;
$isAssoc=$args!==array_values($args); $isAssoc = $args !== array_values($args);
foreach($args as $key => $value) foreach ($args as $key => $value)
{ {
$count++; $count++;
if($count>=5) if ($count >= 5) {
{ if ($count > 5)
if($count>5)
unset($args[$key]); unset($args[$key]);
else else
$args[$key]='...'; $args[$key] = '...';
continue; continue;
} }
if(is_object($value)) if (is_object($value))
$args[$key] = get_class($value); $args[$key] = get_class($value);
else if(is_bool($value)) else if (is_bool($value))
$args[$key] = $value ? 'true' : 'false'; $args[$key] = $value ? 'true' : 'false';
else if(is_string($value)) else if (is_string($value)) {
{ if (strlen($value) > 64)
if(strlen($value)>64) $args[$key] = '"' . substr($value, 0, 64) . '..."';
$args[$key] = '"'.substr($value,0,64).'..."';
else else
$args[$key] = '"'.$value.'"'; $args[$key] = '"' . $value . '"';
} }
else if(is_array($value)) else if (is_array($value))
$args[$key] = 'array('.$this->argumentsToString($value).')'; $args[$key] = 'array(' . $this->argumentsToString($value) . ')';
else if($value===null) else if ($value === null)
$args[$key] = 'null'; $args[$key] = 'null';
else if(is_resource($value)) else if (is_resource($value))
$args[$key] = 'resource'; $args[$key] = 'resource';
if(is_string($key)) if (is_string($key)) {
{ $args[$key] = '"' . $key . '" => ' . $args[$key];
$args[$key] = '"'.$key.'" => '.$args[$key];
} }
else if($isAssoc) else if ($isAssoc) {
{ $args[$key] = $key . ' => ' . $args[$key];
$args[$key] = $key.' => '.$args[$key];
} }
} }
$out = implode(", ", $args); $out = implode(", ", $args);
@ -446,10 +445,9 @@ class CErrorHandler extends CApplicationComponent
*/ */
protected function isCoreCode($trace) protected function isCoreCode($trace)
{ {
if(isset($trace['file'])) if (isset($trace['file'])) {
{ $systemPath = realpath(dirname(__FILE__) . '/..');
$systemPath=realpath(dirname(__FILE__).'/..'); return $trace['file'] === 'unknown' || strpos(realpath($trace['file']), $systemPath . DIRECTORY_SEPARATOR) === 0;
return $trace['file']==='unknown' || strpos(realpath($trace['file']),$systemPath.DIRECTORY_SEPARATOR)===0;
} }
return false; return false;
} }
@ -461,27 +459,49 @@ class CErrorHandler extends CApplicationComponent
* @param integer $maxLines maximum number of lines to display * @param integer $maxLines maximum number of lines to display
* @return string the rendering result * @return string the rendering result
*/ */
protected function renderSourceCode($file,$errorLine,$maxLines) protected function renderSourceCode($file, $errorLine, $maxLines)
{ {
$errorLine--; // adjust line number to 0-based from 1-based $errorLine--; // adjust line number to 0-based from 1-based
if($errorLine<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$errorLine) if ($errorLine < 0 || ($lines = @file($file)) === false || ($lineCount = count($lines)) <= $errorLine)
return ''; return '';
$halfLines=(int)($maxLines/2); $halfLines = (int)($maxLines / 2);
$beginLine=$errorLine-$halfLines>0 ? $errorLine-$halfLines:0; $beginLine = $errorLine - $halfLines > 0 ? $errorLine - $halfLines : 0;
$endLine=$errorLine+$halfLines<$lineCount?$errorLine+$halfLines:$lineCount-1; $endLine = $errorLine + $halfLines < $lineCount ? $errorLine + $halfLines : $lineCount - 1;
$lineNumberWidth=strlen($endLine+1); $lineNumberWidth = strlen($endLine + 1);
$output=''; $output = '';
for($i=$beginLine;$i<=$endLine;++$i) for ($i = $beginLine; $i <= $endLine; ++$i)
{ {
$isErrorLine = $i===$errorLine; $isErrorLine = $i === $errorLine;
$code=sprintf("<span class=\"ln".($isErrorLine?' error-ln':'')."\">%0{$lineNumberWidth}d</span> %s",$i+1,CHtml::encode(str_replace("\t",' ',$lines[$i]))); $code = sprintf("<span class=\"ln" . ($isErrorLine ? ' error-ln' : '') . "\">%0{$lineNumberWidth}d</span> %s", $i + 1, CHtml::encode(str_replace("\t", ' ', $lines[$i])));
if(!$isErrorLine) if (!$isErrorLine)
$output.=$code; $output .= $code;
else else
$output.='<span class="error">'.$code.'</span>'; $output .= '<span class="error">' . $code . '</span>';
} }
return '<div class="code"><pre>'.$output.'</pre></div>'; return '<div class="code"><pre>' . $output . '</pre></div>';
}
/**
* Handles PHP execution errors such as warnings, notices.
*
* This method is implemented as a PHP error handler. It requires
* that constant YII_ENABLE_ERROR_HANDLER be defined true.
*
* This method will first raise an `error` event.
* If the error is not handled by any event handler, it will call
* {@link getErrorHandler errorHandler} to process the error.
*
* The application will be terminated by this method.
*
* @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
*/
public function handleError($code, $message, $file, $line)
{
throw new \ErrorException($message, 0, $code, $file, $line);
} }
} }

74
framework/base/StatePersister.php

@ -1,74 +0,0 @@
<?php
/**
* StatePersister class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* CStatePersister implements a file-based persistent data storage.
*
* It can be used to keep data available through multiple requests and sessions.
*
* By default, CStatePersister stores data in a file named 'state.bin' that is located
* under the application {@link CApplication::getRuntimePath runtime path}.
* You may change the location by setting the {@link stateFile} property.
*
* To retrieve the data from CStatePersister, call {@link load()}. To save the data,
* call {@link save()}.
*
* Comparison among state persister, session and cache is as follows:
* <ul>
* <li>session: data persisting within a single user session.</li>
* <li>state persister: data persisting through all requests/sessions (e.g. hit counter).</li>
* <li>cache: volatile and fast storage. It may be used as storage medium for session or state persister.</li>
* </ul>
*
* Since server resource is often limited, be cautious if you plan to use CStatePersister
* to store large amount of data. You should also consider using database-based persister
* to improve the throughput.
*
* CStatePersister is a core application component used to store global application state.
* It may be accessed via {@link CApplication::getStatePersister()}.
* page state persistent method based on cache.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class StatePersister extends ApplicationComponent
{
/**
* @var string the file path for keeping the state data. Make sure the directory containing
* the file exists and is writable by the Web server process. If using relative path, also
* make sure the path is correct. You may use a path alias here. If not set, it defaults
* to the `state.bin` file under the application's runtime directory.
*/
public $dataFile;
/**
* Loads state data from persistent storage.
* @return mixed state data. Null if no state data available.
*/
public function load()
{
$dataFile = \Yii::getAlias($this->dataFile);
if (is_file($dataFile) && ($data = file_get_contents($dataFile)) !== false) {
return unserialize($data);
} else {
return null;
}
}
/**
* Saves application state in persistent storage.
* @param mixed $state state data (must be serializable).
*/
public function save($state)
{
file_put_contents(\Yii::getAlias($this->dataFile), serialize($state), LOCK_EX);
}
}

27
framework/base/View.php

@ -0,0 +1,27 @@
<?php
/**
* View class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class View extends Component
{
public function render($context, $_file_, $_data_ = array())
{
// we use special variable names here to avoid conflict with extracted variables
extract($_data_, EXTR_PREFIX_SAME, 'data');
ob_start();
ob_implicit_flush(false);
require($_file_);
return ob_get_clean();
}
}

11
framework/db/ar/ActiveQuery.php

@ -91,8 +91,7 @@ class ActiveQuery extends BaseActiveQuery implements \IteratorAggregate, \ArrayA
*/ */
public function value() public function value()
{ {
$finder = new ActiveFinder($this->getDbConnection()); return $this->createFinder()->find($this, true);
return $finder->find($this, true);
} }
public function exists() public function exists()
@ -234,7 +233,11 @@ class ActiveQuery extends BaseActiveQuery implements \IteratorAggregate, \ArrayA
protected function findRecords() protected function findRecords()
{ {
$finder = new ActiveFinder($this->getDbConnection()); return $this->createFinder()->find($this);
return $finder->find($this); }
protected function createFinder()
{
return new ActiveFinder($this->getDbConnection());
} }
} }

10
framework/db/ar/ActiveRecord.php

@ -89,7 +89,9 @@ abstract class ActiveRecord extends Model
* // find all customers * // find all customers
* $customers = Customer::find()->all(); * $customers = Customer::find()->all();
* // find a single customer whose primary key value is 10 * // find a single customer whose primary key value is 10
* $customer = Customer::find(10)->one(); * $customer = Customer::find(10);
* // the above is equivalent to:
* Customer::find()->where(array('id' => 10))->one();
* // find all active customers and order them by their age: * // find all active customers and order them by their age:
* $customers = Customer::find() * $customers = Customer::find()
* ->where(array('status' => 1)) * ->where(array('status' => 1))
@ -107,7 +109,9 @@ abstract class ActiveRecord extends Model
* - a scalar value (integer or string): query by a single primary key value. * - a scalar value (integer or string): query by a single primary key value.
* - an array of name-value pairs: it will be used to configure the [[ActiveQuery]] object. * - an array of name-value pairs: it will be used to configure the [[ActiveQuery]] object.
* *
* @return ActiveQuery the [[ActiveQuery]] instance for query purpose. * @return ActiveQuery|ActiveRecord|null the [[ActiveQuery]] instance for query purpose, or
* the ActiveRecord object when a scalar is passed to this method which is considered to be a
* primary key value (null will be returned if no record is found in this case.)
*/ */
public static function find($q = null) public static function find($q = null)
{ {
@ -119,7 +123,7 @@ abstract class ActiveRecord extends Model
} elseif ($q !== null) { } elseif ($q !== null) {
// query by primary key // query by primary key
$primaryKey = static::getMetaData()->table->primaryKey; $primaryKey = static::getMetaData()->table->primaryKey;
$query->where(array($primaryKey[0] => $q)); return $query->where(array($primaryKey[0] => $q))->one();
} }
return $query; return $query;
} }

16
framework/logging/Logger.php

@ -152,7 +152,7 @@ class Logger extends \yii\base\Component
$count = 0; $count = 0;
foreach ($traces as $trace) { foreach ($traces as $trace) {
if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII_PATH) !== 0) { if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII_PATH) !== 0) {
$message .= "\nin " . $trace['file'] . ' (' . $trace['line'] . ')'; $message .= "\nin {$trace['file']} ({$trace['line']})";
if (++$count >= YII_TRACE_LEVEL) { if (++$count >= YII_TRACE_LEVEL) {
break; break;
} }
@ -174,20 +174,14 @@ class Logger extends \yii\base\Component
*/ */
public function flush($export = false) public function flush($export = false)
{ {
$this->onFlush(new \yii\base\Event($this, array('export' => $export, 'flush' => true))); $this->trigger('flush', new \yii\base\Event($this, array(
'export' => $export,
'flush' => true,
)));
$this->messages = array(); $this->messages = array();
} }
/** /**
* Raises a `flush` event.
* @param \yii\base\Event $event the event parameter
*/
public function onFlush($event)
{
$this->trigger('flush', $event);
}
/**
* Returns the total elapsed time since the start of the current request. * Returns the total elapsed time since the start of the current request.
* This method calculates the difference between now and the timestamp * This method calculates the difference between now and the timestamp
* defined by constant `YII_BEGIN_TIME` which is evaluated at the beginning * defined by constant `YII_BEGIN_TIME` which is evaluated at the beginning

17
framework/logging/Router.php

@ -56,6 +56,9 @@ namespace yii\logging;
*/ */
class Router extends \yii\base\ApplicationComponent class Router extends \yii\base\ApplicationComponent
{ {
/**
* @var \yii\base\Dictionary
*/
private $_targets; private $_targets;
/** /**
@ -69,15 +72,15 @@ class Router extends \yii\base\ApplicationComponent
/** /**
* Initializes this application component. * Initializes this application component.
* This method is invoked when the Router component is created by the application. * This method is invoked when the Router component is created by the application.
* The method attaches the [[processLogs]] method to both the [[Logger::onFlush]] event * The method attaches the [[processLogs]] method to both the [[Logger::flush]] event
* and the [[\yii\base\Application::onEndRequest]] event. * and the [[\yii\base\Application::afterRequest]] event.
*/ */
public function init() public function init()
{ {
parent::init(); parent::init();
\Yii::getLogger()->attachEventHandler('onFlush', array($this, 'processMessages')); \Yii::getLogger()->on('flush', array($this, 'processMessages'));
if (($app = \Yii::$application) !== null) { if (($app = \Yii::$application) !== null) {
$app->attachEventHandler('onEndRequest', array($this, 'processMessages')); $app->on('afterRequest', array($this, 'processMessages'));
} }
} }
@ -100,7 +103,7 @@ class Router extends \yii\base\ApplicationComponent
* Sets the log targets. * Sets the log targets.
* @param array $config list of log target configurations. Each array element * @param array $config list of log target configurations. Each array element
* represents the configuration for creating a single log target. It will be * represents the configuration for creating a single log target. It will be
* passed to [[\Yii::createObject]] to create the target instance. * passed to [[\Yii::createObject()]] to create the target instance.
*/ */
public function setTargets($config) public function setTargets($config)
{ {
@ -124,8 +127,8 @@ class Router extends \yii\base\ApplicationComponent
public function processMessages($event) public function processMessages($event)
{ {
$messages = \Yii::getLogger()->messages; $messages = \Yii::getLogger()->messages;
$export = !isset($event->params['export']) || $event->params['export']; $export = !isset($event->data['export']) || $event->data['export'];
$final = !isset($event->params['flush']) || !$event->params['flush']; $final = !isset($event->data['flush']) || !$event->data['flush'];
foreach ($this->_targets as $target) { foreach ($this->_targets as $target) {
if ($target->enabled) { if ($target->enabled) {
$target->processMessages($messages, $export, $final); $target->processMessages($messages, $export, $final);

40
framework/web/HttpException.php

@ -1,40 +0,0 @@
<?php
/**
* HttpException class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
/**
* CHttpException represents an exception caused by invalid operations of end-users.
*
* The HTTP error code can be obtained via {@link statusCode}.
* Error handlers may use this status code to decide how to format the error page.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class HttpException extends \yii\base\Exception
{
/**
* @var integer HTTP status code, such as 403, 404, 500, etc.
*/
public $statusCode;
/**
* Constructor.
* @param integer $status HTTP status code, such as 404, 500, etc.
* @param string $message error message
* @param integer $code error code
*/
public function __construct($status,$message=null,$code=0)
{
$this->statusCode=$status;
parent::__construct($message,$code);
}
}
Loading…
Cancel
Save