Commit ba6c10eb by Qiang Xue

Yii debugger WIP

parent 682c0a34
......@@ -77,7 +77,10 @@ class Action extends Component
throw new InvalidConfigException(get_class($this) . ' must define a "run()" method.');
}
$args = $this->controller->bindActionParams($this, $params);
Yii::trace('Running "' . get_class($this) . '::run()" with parameters: ' . var_export($args, true), __METHOD__);
Yii::info('Running "' . get_class($this) . '::run()" with parameters: ' . var_export($args, true), __METHOD__);
if (Yii::$app->requestedParams === null) {
Yii::$app->requestedParams = $args;
}
return call_user_func_array(array($this, 'run'), $args);
}
}
......@@ -78,6 +78,18 @@ abstract class Application extends Module
* Defaults to 256KB.
*/
public $memoryReserveSize = 262144;
/**
* @var string the requested route
*/
public $requestedRoute;
/**
* @var Action the requested Action. If null, it means the request cannot be resolved into an action.
*/
public $requestedAction;
/**
* @var array the parameters supplied to the requested action.
*/
public $requestedParams;
/**
* @var string Used to reserve memory for fatal error handler.
......
......@@ -108,6 +108,9 @@ class Controller extends Component
$action = $this->createAction($id);
if ($action !== null) {
Yii::trace("Route to run: " . $action->getUniqueId(), __METHOD__);
if (Yii::$app->requestedAction === null) {
Yii::$app->requestedAction = $action;
}
$oldAction = $this->action;
$this->action = $action;
$result = null;
......
......@@ -46,7 +46,10 @@ class InlineAction extends Action
public function runWithParams($params)
{
$args = $this->controller->bindActionParams($this, $params);
Yii::trace("Running '" . get_class($this->controller) . '::' . $this->actionMethod . "()' with parameters: " . var_export($args, true), __METHOD__);
Yii::info("Running '" . get_class($this->controller) . '::' . $this->actionMethod . "()' with parameters: " . var_export($args, true), __METHOD__);
if (Yii::$app->requestedParams === null) {
Yii::$app->requestedParams = $args;
}
return call_user_func_array(array($this->controller, $this->actionMethod), $args);
}
}
......@@ -92,6 +92,7 @@ class Application extends \yii\base\Application
public function handleRequest($request)
{
list ($route, $params) = $request->resolve();
$this->requestedRoute = $route;
$result = $this->runAction($route, $params);
if ($result instanceof Response) {
return $result;
......
......@@ -23,6 +23,10 @@ class LogTarget extends Target
public $tag;
public $historySize = 20;
/**
* @param \yii\debug\Module $module
* @param array $config
*/
public function __construct($module, $config = array())
{
parent::__construct($config);
......@@ -42,8 +46,8 @@ class LogTarget extends Target
}
$file = "$path/{$this->tag}.log";
$data = array();
foreach ($this->module->panels as $panel) {
$data[$panel->id] = $panel->save();
foreach ($this->module->panels as $id => $panel) {
$data[$id] = $panel->save();
}
file_put_contents($file, json_encode($data));
}
......@@ -58,7 +62,7 @@ class LogTarget extends Target
*/
public function collect($messages, $final)
{
$this->messages = array_merge($this->messages, $this->filterMessages($messages));
$this->messages = array_merge($this->messages, $messages);
if ($final) {
$this->export($this->messages);
$this->gc();
......
......@@ -28,6 +28,10 @@ class Module extends \yii\base\Module
public $controllerNamespace = 'yii\debug\controllers';
/**
* @var LogTarget
*/
public $logTarget;
/**
* @var array|Panel[]
*/
public $panels = array();
......@@ -36,19 +40,20 @@ class Module extends \yii\base\Module
{
parent::init();
$this->logTarget = Yii::$app->getLog()->targets['debug'] = new LogTarget($this);
Yii::$app->getView()->on(View::EVENT_END_BODY, array($this, 'renderToolbar'));
foreach (array_merge($this->corePanels(), $this->panels) as $id => $config) {
$config['id'] = $id;
$config['module'] = $this;
$this->panels[$id] = Yii::createObject($config);
}
Yii::$app->getLog()->targets['debug'] = new LogTarget($this);
Yii::$app->getView()->on(View::EVENT_END_BODY, array($this, 'renderToolbar'));
}
public function beforeAction($action)
{
Yii::$app->getView()->off(View::EVENT_END_BODY, array($this, 'renderToolbar'));
unset(Yii::$app->getLog()->targets['debug']);
$this->logTarget = null;
$ip = Yii::$app->getRequest()->getUserIP();
foreach ($this->allowedIPs as $filter) {
......@@ -63,7 +68,7 @@ class Module extends \yii\base\Module
{
/** @var View $view */
$id = 'yii-debug-toolbar';
$tag = Yii::$app->getLog()->targets['debug']->tag;
$tag = $this->logTarget->tag;
$url = Yii::$app->getUrlManager()->createUrl('debug/default/toolbar', array(
'tag' => $tag,
));
......@@ -88,6 +93,12 @@ class Module extends \yii\base\Module
'log' => array(
'class' => 'yii\debug\panels\LogPanel',
),
'profiling' => array(
'class' => 'yii\debug\panels\ProfilingPanel',
),
'db' => array(
'class' => 'yii\debug\panels\DbPanel',
),
);
}
}
......@@ -15,7 +15,10 @@ use yii\base\Component;
*/
class Panel extends Component
{
public $id;
/**
* @var Module
*/
public $module;
public $data;
public function getName()
......
......@@ -51,8 +51,8 @@ class DefaultController extends Controller
if (preg_match('/^[\w\-]+$/', $tag) && is_file($file)) {
$data = json_decode(file_get_contents($file), true);
foreach ($this->module->panels as $id => $panel) {
if (isset($data[$panel->id])) {
$panel->load($data[$panel->id]);
if (isset($data[$id])) {
$panel->load($data[$id]);
} else {
// remove the panel since it has not received any data
unset($this->module->panels[$id]);
......
......@@ -9,7 +9,6 @@ namespace yii\debug\panels;
use Yii;
use yii\debug\Panel;
use yii\helpers\Html;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\debug\panels;
use yii\debug\Panel;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DbPanel extends Panel
{
public function getName()
{
return 'Database';
}
}
......@@ -40,10 +40,21 @@ EOD;
$time = date('H:i:s.', $log[3]) . sprintf('%03d', (int)(($log[3] - (int)$log[3]) * 1000));
$level = Logger::getLevelName($log[1]);
$message = Html::encode(wordwrap($log[0]));
$rows[] = "<tr><td style=\"width: 100px;\">$time</td><td style=\"width: 100px;\">$level</td><td style=\"width: 250px;\">{$log[2]}</td><td>$message</td></tr>";
if ($log[1] == Logger::LEVEL_ERROR) {
$class = ' class="error"';
} elseif ($log[1] == Logger::LEVEL_WARNING) {
$class = ' class="warning"';
} elseif ($log[1] == Logger::LEVEL_INFO) {
$class = ' class="info"';
} else {
$class = '';
}
$rows[] = "<tr$class><td style=\"width: 100px;\">$time</td><td style=\"width: 100px;\">$level</td><td style=\"width: 250px;\">{$log[2]}</td><td>$message</td></tr>";
}
$rows = implode("\n", $rows);
return <<<EOD
<h1>Log Messages</h1>
<table class="table table-condensed table-bordered table-striped table-hover" style="table-layout: fixed;">
<thead>
<tr>
......@@ -62,8 +73,10 @@ EOD;
public function save()
{
$target = $this->module->logTarget;
$messages = $target->filterMessages($target->messages, Logger::LEVEL_ERROR | Logger::LEVEL_INFO | Logger::LEVEL_WARNING | Logger::LEVEL_TRACE);
return array(
'messages' => Yii::$app->getLog()->targets['debug']->messages,
'messages' => $messages,
);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\debug\panels;
use Yii;
use yii\debug\Panel;
use yii\helpers\Html;
use yii\log\Logger;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ProfilingPanel extends Panel
{
public function getName()
{
return 'Profiling';
}
public function getDetail()
{
$messages = $this->data['messages'];
$timings = array();
$stack = array();
foreach ($messages as $i => $log) {
list($token, $level, $category, $timestamp) = $log;
$log[4] = $i;
if ($level == Logger::LEVEL_PROFILE_BEGIN) {
$stack[] = $log;
} elseif ($level == Logger::LEVEL_PROFILE_END) {
if (($last = array_pop($stack)) !== null && $last[0] === $token) {
$timings[$last[4]] = array(count($stack), $token, $category, $timestamp - $last[3]);
}
}
}
$now = microtime(true);
while (($last = array_pop($stack)) !== null) {
$delta = $now - $last[3];
$timings[$last[4]] = array(count($stack), $last[0], $last[2], $delta);
}
ksort($timings);
$rows = array();
foreach ($timings as $timing) {
$time = sprintf('%0.5f', $timing[3]);
$procedure = str_repeat('&nbsp;', $timing[0] * 4) . Html::encode($timing[1]);
$category = Html::encode($timing[2]);
$rows[] = "<tr><td>$category</td><td>$procedure</td><td>{$time}s</td>";
}
$rows = implode("\n", $rows);
return <<<EOD
<h1>Performance Profiling</h1>
<table class="table table-condensed table-bordered table-striped table-hover" style="table-layout: fixed;">
<thead>
<tr>
<th>Category</th>
<th>Procedure</th>
<th>Time</th>
</tr>
</thead>
<tbody>
$rows
</tbody>
</table>
EOD;
}
public function save()
{
$target = $this->module->logTarget;
$messages = $target->filterMessages($target->messages, Logger::LEVEL_PROFILE);
return array(
'messages' => $messages,
);
}
}
......@@ -7,6 +7,8 @@
namespace yii\debug\panels;
use Yii;
use yii\base\InlineAction;
use yii\debug\Panel;
use yii\helpers\Html;
......@@ -39,37 +41,92 @@ EOD;
public function getDetail()
{
return "<h3>\$_GET</h3>\n" . $this->renderTable($this->data['GET']) . "\n"
. "<h3>\$_POST</h3>\n" . $this->renderTable($this->data['POST']) . "\n"
. "<h3>\$_COOKIE</h3>\n" . $this->renderTable($this->data['COOKIE']) . "\n"
. "<h3>\$_FILES</h3>\n" . $this->renderTable($this->data['FILES']) . "\n"
. "<h3>\$_SESSION</h3>\n" . $this->renderTable($this->data['SESSION']) . "\n"
. "<h3>\$_SERVER</h3>\n" . $this->renderTable($this->data['SERVER']);
$data = array(
'Route' => $this->data['route'],
'Action' => $this->data['action'],
'Parameters' => $this->data['actionParams'],
);
return "<h1>Request Information</h1>\n"
. $this->renderData('Routing', $data) . "\n"
. $this->renderData('Flashes', $this->data['flashes']) . "\n"
. $this->renderData('$_GET', $this->data['GET']) . "\n"
. $this->renderData('$_POST', $this->data['POST']) . "\n"
. $this->renderData('$_COOKIE', $this->data['COOKIE']) . "\n"
. $this->renderData('$_FILES', $this->data['FILES']) . "\n"
. $this->renderData('$_SESSION', $this->data['SESSION']) . "\n"
. $this->renderData('$_SERVER', $this->data['SERVER']) . "\n"
. $this->renderData('Request Headers', $this->data['requestHeaders']) . "\n"
. $this->renderData('Response Headers', $this->data['responseHeaders']);
}
public function save()
{
if (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
} elseif (function_exists('http_get_request_headers')) {
$requestHeaders = http_get_request_headers();
} else {
$requestHeaders = array();
}
$responseHeaders = array();
foreach (headers_list() as $header) {
if (($pos = strpos($header, ':')) !== false) {
$name = substr($header, 0, $pos);
$value = trim(substr($header, $pos + 1));
if (isset($responseHeaders[$name])) {
if (!is_array($responseHeaders[$name])) {
$responseHeaders[$name] = array($responseHeaders[$name], $value);
} else {
$responseHeaders[$name][] = $value;
}
} else {
$responseHeaders[$name] = $value;
}
} else {
$responseHeaders[] = $header;
}
}
if (Yii::$app->requestedAction) {
if (Yii::$app->requestedAction instanceof InlineAction) {
$action = get_class(Yii::$app->requestedAction->controller) . '::' . Yii::$app->requestedAction->actionMethod . '()';
} else {
$action = get_class(Yii::$app->requestedAction) . '::run()';
}
} else {
$action = null;
}
/** @var \yii\web\Session $session */
$session = Yii::$app->getComponent('session', false);
return array(
'memory' => memory_get_peak_usage(),
'time' => microtime(true) - YII_BEGIN_TIME,
'SERVER' => $_SERVER,
'GET' => $_GET,
'POST' => $_POST,
'COOKIE' => $_COOKIE,
'flashes' => $session ? $session->getAllFlashes() : array(),
'requestHeaders' => $requestHeaders,
'responseHeaders' => $responseHeaders,
'route' => Yii::$app->requestedAction->getUniqueId(),
'action' => $action,
'actionParams' => Yii::$app->requestedParams,
'SERVER' => empty($_SERVER) ? array() : $_SERVER,
'GET' => empty($_GET) ? array() : $_GET,
'POST' => empty($_POST) ? array() : $_POST,
'COOKIE' => empty($_COOKIE) ? array() : $_COOKIE,
'FILES' => empty($_FILES) ? array() : $_FILES,
'SESSION' => empty($_SESSION) ? array() : $_SESSION,
);
}
protected function renderTable($values)
protected function renderData($caption, $values)
{
if (empty($values)) {
return "<h3>$caption</h3>\n<p>Empty.</p>";
}
$rows = array();
foreach ($values as $name => $value) {
$rows[] = '<tr><th style="width: 200px;">' . Html::encode($name) . '</th><td><div style="overflow:auto">' . Html::encode(var_export($value, true)) . '</div></td></tr>';
}
if (!empty($rows)) {
$rows = implode("\n", $rows);
return <<<EOD
<h3>$caption</h3>
<table class="table table-condensed table-bordered table-striped table-hover" style="table-layout: fixed;">
<thead><tr><th style="width: 200px;">Name</th><th>Value</th></tr></thead>
<tbody>
......@@ -77,8 +134,5 @@ $rows
</tbody>
</table>
EOD;
} else {
return 'Empty.';
}
}
}
......@@ -24,8 +24,8 @@ use yii\helpers\Html;
<div class="well sidebar-nav">
<ul class="nav nav-list">
<?php
foreach ($panels as $panel) {
$link = Html::a(Html::encode($panel->getName()), array('debug/default/index', 'tag' => $tag, 'panel' => $panel->id));
foreach ($panels as $id => $panel) {
$link = Html::a(Html::encode($panel->getName()), array('debug/default/index', 'tag' => $tag, 'panel' => $id));
echo Html::tag('li', $link, array('class' => $panel === $activePanel ? 'active' : null));
}
?>
......
......@@ -90,7 +90,7 @@ abstract class Target extends Component
*/
public function collect($messages, $final)
{
$this->messages = array_merge($this->messages, $this->filterMessages($messages));
$this->messages = array_merge($this->messages, $this->filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
$count = count($this->messages);
if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
if (($context = $this->getContextMessage()) !== '') {
......@@ -178,22 +178,22 @@ abstract class Target extends Component
/**
* Filters the given messages according to their categories and levels.
* @param array $messages messages to be filtered
* @param integer $levels the message levels to filter by. This is a bitmap of
* level values. Value 0 means allowing all levels.
* @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
* @param array $except the message categories to exclude. If empty, it means all categories are allowed.
* @return array the filtered messages.
* @see filterByCategory
* @see filterByLevel
*/
protected function filterMessages($messages)
public function filterMessages($messages, $levels = 0, $categories = array(), $except = array())
{
$levels = $this->getLevels();
foreach ($messages as $i => $message) {
if ($levels && !($levels & $message[1])) {
unset($messages[$i]);
continue;
}
$matched = empty($this->categories);
foreach ($this->categories as $category) {
$matched = empty($categories);
foreach ($categories as $category) {
if ($message[2] === $category || substr($category, -1) === '*' && strpos($message[2], rtrim($category, '*')) === 0) {
$matched = true;
break;
......@@ -201,7 +201,7 @@ abstract class Target extends Component
}
if ($matched) {
foreach ($this->except as $category) {
foreach ($except as $category) {
$prefix = rtrim($category, '*');
if (strpos($message[2], $prefix) === 0 && ($message[2] === $category || $prefix !== $category)) {
$matched = false;
......
......@@ -66,6 +66,7 @@ class Application extends \yii\base\Application
}
try {
Yii::trace("Route requested: '$route'", __METHOD__);
$this->requestedRoute = $route;
$result = $this->runAction($route, $params);
if ($result instanceof Response) {
return $result;
......
......@@ -171,6 +171,7 @@ class UrlManager extends Component
/** @var $rule UrlRule */
foreach ($this->rules as $rule) {
if (($result = $rule->parseRequest($this, $request)) !== false) {
Yii::info("Request parsed with URL rule: {$rule->name}", __METHOD__);
return $result;
}
}
......@@ -194,12 +195,14 @@ class UrlManager extends Component
}
}
Yii::info('No matching URL rules. Using default URL parsing logic.', __METHOD__);
return array($pathInfo, array());
} else {
$route = $request->get($this->routeVar);
if (is_array($route)) {
$route = '';
}
Yii::info('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
return array((string)$route, array());
}
}
......
......@@ -7,6 +7,12 @@ use yiiunit\TestCase;
class UrlManagerTest extends TestCase
{
protected function setUp()
{
parent::setUp();
$this->mockApplication();
}
public function testCreateUrl()
{
// default setting with '/' as base url
......
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