[VarDumper] Dump PHP+Twig code excerpts in backtraces

This commit is contained in:
Nicolas Grekas 2015-09-19 16:06:18 +02:00
parent 74c24a5315
commit 89578f15c5
7 changed files with 316 additions and 27 deletions

View File

@ -42,12 +42,12 @@ class ExceptionCaster
public static function castError(\Error $e, array $a, Stub $stub, $isNested, $filter = 0)
{
return self::filterExceptionArray($a, "\0Error\0", $filter);
return self::filterExceptionArray($stub->class, $a, "\0Error\0", $filter);
}
public static function castException(\Exception $e, array $a, Stub $stub, $isNested, $filter = 0)
{
return self::filterExceptionArray($a, "\0Exception\0", $filter);
return self::filterExceptionArray($stub->class, $a, "\0Exception\0", $filter);
}
public static function castErrorException(\ErrorException $e, array $a, Stub $stub, $isNested)
@ -64,24 +64,133 @@ class ExceptionCaster
$prefix = Caster::PREFIX_PROTECTED;
$xPrefix = "\0Exception\0";
if (isset($a[$xPrefix.'previous'], $a[$xPrefix.'trace'][0])) {
if (isset($a[$xPrefix.'previous'], $a[$xPrefix.'trace'])) {
$b = (array) $a[$xPrefix.'previous'];
$b[$xPrefix.'trace'][0] += array(
array_unshift($b[$xPrefix.'trace'], array(
'function' => 'new '.get_class($a[$xPrefix.'previous']),
'file' => $b[$prefix.'file'],
'line' => $b[$prefix.'line'],
);
array_splice($b[$xPrefix.'trace'], -1 - count($a[$xPrefix.'trace']));
static::filterTrace($b[$xPrefix.'trace'], false);
$a[Caster::PREFIX_VIRTUAL.'trace'] = $b[$xPrefix.'trace'];
));
$a[$xPrefix.'trace'] = new TraceStub($b[$xPrefix.'trace'], 1, false, 0, -1 - count($a[$xPrefix.'trace']->value));
}
unset($a[$xPrefix.'trace'], $a[$xPrefix.'previous'], $a[$prefix.'code'], $a[$prefix.'file'], $a[$prefix.'line']);
unset($a[$xPrefix.'previous'], $a[$prefix.'code'], $a[$prefix.'file'], $a[$prefix.'line']);
return $a;
}
public static function castTraceStub(TraceStub $trace, array $a, Stub $stub, $isNested)
{
if (!$isNested) {
return $a;
}
$stub->class = '';
$stub->handle = 0;
$frames = $trace->value;
$a = array();
$j = count($frames);
if (0 > $i = $trace->offset) {
$i = max(0, $j + $i);
}
if (!isset($trace->value[$i])) {
return array();
}
$lastCall = isset($frames[$i]['function']) ? ' ==> '.(isset($frames[$i]['class']) ? $frames[0]['class'].$frames[$i]['type'] : '').$frames[$i]['function'].'()' : '';
for ($j -= $i++; isset($frames[$i]); ++$i, --$j) {
$call = isset($frames[$i]['function']) ? (isset($frames[$i]['class']) ? $frames[$i]['class'].$frames[$i]['type'] : '').$frames[$i]['function'].'()' : '???';
$a[Caster::PREFIX_VIRTUAL.$j.'. '.$call.$lastCall] = new FrameStub(
array(
'object' => isset($frames[$i]['object']) ? $frames[$i]['object'] : null,
'class' => isset($frames[$i]['class']) ? $frames[$i]['class'] : null,
'type' => isset($frames[$i]['type']) ? $frames[$i]['type'] : null,
'function' => isset($frames[$i]['function']) ? $frames[$i]['function'] : null,
) + $frames[$i - 1],
$trace->srcContext,
$trace->keepArgs,
true
);
$lastCall = ' ==> '.$call;
}
$a[Caster::PREFIX_VIRTUAL.$j.'. {main}'.$lastCall] = new FrameStub(
array(
'object' => null,
'class' => null,
'type' => null,
'function' => '{main}',
) + $frames[$i - 1],
$trace->srcContext,
$trace->keepArgs,
true
);
if (null !== $trace->length) {
$a = array_slice($a, 0, $trace->length, true);
}
return $a;
}
public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, $isNested)
{
if (!$isNested) {
return $a;
}
$f = $frame->value;
$prefix = Caster::PREFIX_VIRTUAL;
if (isset($f['file'], $f['line'])) {
if (preg_match('/\((\d+)\)(?:\([\da-f]{32}\))? : (?:eval\(\)\'d code|runtime-created function)$/', $f['file'], $match)) {
$f['file'] = substr($f['file'], 0, -strlen($match[0]));
$f['line'] = (int) $match[1];
}
if (file_exists($f['file']) && 0 <= $frame->srcContext) {
$src[$f['file'].':'.$f['line']] = self::extractSource(explode("\n", file_get_contents($f['file'])), $f['line'], $frame->srcContext);
if (!empty($f['class']) && is_subclass_of($f['class'], 'Twig_Template') && method_exists($f['class'], 'getDebugInfo')) {
$template = isset($f['object']) ? $f['object'] : new $f['class'](new \Twig_Environment(new \Twig_Loader_Filesystem()));
try {
$templateName = $template->getTemplateName();
$templateSrc = explode("\n", method_exists($template, 'getSource') ? $template->getSource() : $template->getEnvironment()->getLoader()->getSource($templateName));
$templateInfo = $template->getDebugInfo();
if (isset($templateInfo[$f['line']])) {
$src[$templateName.':'.$templateInfo[$f['line']]] = self::extractSource($templateSrc, $templateInfo[$f['line']], $frame->srcContext);
}
} catch (\Twig_Error_Loader $e) {
}
}
} else {
$src[$f['file']] = $f['line'];
}
$a[$prefix.'src'] = new EnumStub($src);
}
unset($a[$prefix.'args'], $a[$prefix.'line'], $a[$prefix.'file']);
if ($frame->inTraceStub) {
unset($a[$prefix.'class'], $a[$prefix.'type'], $a[$prefix.'function']);
}
foreach ($a as $k => $v) {
if (!$v) {
unset($a[$k]);
}
}
if ($frame->keepArgs && isset($f['args'])) {
$a[$prefix.'args'] = $f['args'];
}
return $a;
}
/**
* @deprecated since 2.8, to be removed in 3.0. Use the castTraceStub method instead.
*/
public static function filterTrace(&$trace, $dumpArgs, $offset = 0)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Use the castTraceStub method instead.', E_USER_DEPRECATED);
if (0 > $offset || empty($trace[$offset])) {
return $trace = null;
}
@ -111,7 +220,7 @@ class ExceptionCaster
}
}
private static function filterExceptionArray(array $a, $xPrefix, $filter)
private static function filterExceptionArray($xClass, array $a, $xPrefix, $filter)
{
if (isset($a[$xPrefix.'trace'])) {
$trace = $a[$xPrefix.'trace'];
@ -121,11 +230,12 @@ class ExceptionCaster
}
if (!($filter & Caster::EXCLUDE_VERBOSE)) {
static::filterTrace($trace, static::$traceArgs);
if (null !== $trace) {
$a[$xPrefix.'trace'] = $trace;
}
array_unshift($trace, array(
'function' => $xClass ? 'new '.$xClass : null,
'file' => $a[Caster::PREFIX_PROTECTED.'file'],
'line' => $a[Caster::PREFIX_PROTECTED.'line'],
));
$a[$xPrefix.'trace'] = new TraceStub($trace);
}
if (empty($a[$xPrefix.'previous'])) {
unset($a[$xPrefix.'previous']);
@ -134,4 +244,18 @@ class ExceptionCaster
return $a;
}
private static function extractSource(array $srcArray, $line, $srcContext)
{
$src = '';
for ($i = $line - 1 - $srcContext; $i <= $line - 1 + $srcContext; ++$i) {
$src .= (isset($srcArray[$i]) ? $srcArray[$i] : '')."\n";
}
if (!$srcContext) {
$src = trim($src);
}
return $src;
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
/**
* Represents a single backtrace frame as returned by debug_backtrace() or Exception->getTrace().
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class FrameStub extends EnumStub
{
public $srcContext;
public $keepArgs;
public $inTraceStub;
public function __construct(array $trace, $srcContext = 1, $keepArgs = true, $inTraceStub = false)
{
$this->value = $trace;
$this->srcContext = $srcContext;
$this->keepArgs = $keepArgs;
$this->inTraceStub = $inTraceStub;
}
}

View File

@ -0,0 +1,36 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Represents a backtrace as returned by debug_backtrace() or Exception->getTrace().
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class TraceStub extends Stub
{
public $srcContext;
public $keepArgs;
public $offset;
public $length;
public function __construct(array $trace, $srcContext = 1, $keepArgs = true, $offset = 0, $length = null)
{
$this->value = $trace;
$this->srcContext = $srcContext;
$this->keepArgs = $keepArgs;
$this->offset = $offset;
$this->length = $length;
}
}

View File

@ -69,6 +69,8 @@ abstract class AbstractCloner implements ClonerInterface
'Error' => 'Symfony\Component\VarDumper\Caster\ExceptionCaster::castError',
'Symfony\Component\DependencyInjection\ContainerInterface' => 'Symfony\Component\VarDumper\Caster\StubCaster::cutInternals',
'Symfony\Component\VarDumper\Exception\ThrowingCasterException' => 'Symfony\Component\VarDumper\Caster\ExceptionCaster::castThrowingCasterException',
'Symfony\Component\VarDumper\Caster\TraceStub' => 'Symfony\Component\VarDumper\Caster\ExceptionCaster::castTraceStub',
'Symfony\Component\VarDumper\Caster\FrameStub' => 'Symfony\Component\VarDumper\Caster\ExceptionCaster::castFrameStub',
'PHPUnit_Framework_MockObject_MockObject' => 'Symfony\Component\VarDumper\Caster\StubCaster::cutInternals',
'Prophecy\Prophecy\ProphecySubjectInterface' => 'Symfony\Component\VarDumper\Caster\StubCaster::cutInternals',

View File

@ -170,6 +170,9 @@ EOTXT
{
$out = fopen('php://memory', 'r+b');
require_once __DIR__.'/Fixtures/Twig.php';
$twig = new \__TwigTemplate_VarDumperFixture_u75a09(new \Twig_Environment(new \Twig_Loader_Filesystem()));
$dumper = new CliDumper();
$dumper->setColors(false);
$cloner = new VarCloner();
@ -181,12 +184,15 @@ EOTXT
},
));
$cloner->addCasters(array(
':stream' => function () {
throw new \Exception('Foobar');
},
':stream' => eval('return function () use ($twig) {
try {
$twig->render(array());
} catch (\Twig_Error_Runtime $e) {
throw $e->getPrevious();
}
};'),
));
$line = __LINE__ - 3;
$file = __FILE__;
$line = __LINE__ - 2;
$ref = (int) $out;
$data = $cloner->cloneVar($out);
@ -194,6 +200,19 @@ EOTXT
rewind($out);
$out = stream_get_contents($out);
if (method_exists($twig, 'getSource')) {
$twig = <<<EOTXT
foo.twig:2: """
foo bar\\n
twig source\\n
\\n
"""
EOTXT;
} else {
$twig = '';
}
$r = defined('HHVM_VERSION') ? '' : '#%d';
$this->assertStringMatchesFormat(
<<<EOTXT
@ -210,12 +229,53 @@ stream resource {@{$ref}
options: []
: Symfony\Component\VarDumper\Exception\ThrowingCasterException {{$r}
#message: "Unexpected Exception thrown from a caster: Foobar"
trace: array:1 [
0 => array:2 [
"call" => "%slosure%s()"
"file" => "{$file}:{$line}"
]
]
-trace: {
%d. __TwigTemplate_VarDumperFixture_u75a09->doDisplay() ==> new Exception(): {
src: {
%sTwig.php:19: """
// line 2\\n
throw new \Exception('Foobar');\\n
}\\n
"""
{$twig} }
}
%d. Twig_Template->displayWithErrorHandling() ==> __TwigTemplate_VarDumperFixture_u75a09->doDisplay(): {
src: {
%sTemplate.php:%d: """
try {\\n
\$this->doDisplay(\$context, \$blocks);\\n
} catch (Twig_Error \$e) {\\n
"""
}
}
%d. Twig_Template->display() ==> Twig_Template->displayWithErrorHandling(): {
src: {
%sTemplate.php:%d: """
{\\n
\$this->displayWithErrorHandling(\$this->env->mergeGlobals(\$context), array_merge(\$this->blocks, \$blocks));\\n
}\\n
"""
}
}
%d. Twig_Template->render() ==> Twig_Template->display(): {
src: {
%sTemplate.php:%d: """
try {\\n
\$this->display(\$context);\\n
} catch (Exception \$e) {\\n
"""
}
}
%d. %slosure%s() ==> Twig_Template->render(): {
src: {
%sCliDumperTest.php:{$line}: """
}\\n
};'),\\n
));\\n
"""
}
}
}
}
}

View File

@ -0,0 +1,34 @@
<?php
/* foo.twig */
class __TwigTemplate_VarDumperFixture_u75a09 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 2
throw new \Exception('Foobar');
}
public function getTemplateName()
{
return 'foo.twig';
}
public function getDebugInfo()
{
return array (19 => 2);
}
}
/* foo bar*/
/* twig source*/
/* */

View File

@ -19,7 +19,8 @@
"php": ">=5.3.9"
},
"require-dev": {
"symfony/phpunit-bridge": "~2.7|~3.0.0"
"symfony/phpunit-bridge": "~2.7|~3.0.0",
"twig/twig": "~1.20|~2.0"
},
"suggest": {
"ext-symfony_debug": ""