feature #18466 [Bridge][Twig] Optionally pass dumper into DumpExtension (CarsonF)

This PR was merged into the 3.2-dev branch.

Discussion
----------

[Bridge][Twig] Optionally pass dumper into DumpExtension

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT

Allow the dumper to be passed into `DumpExtension` constructor. This allows a different dumper to be used or even just `HtmlDumper` with a non-default configuration, such as different styles.

Note: The dumper's output is ignored.

Commits
-------

d8c0f1d [Bridge][Twig] Optionally pass dumper into DumpExtension
This commit is contained in:
Fabien Potencier 2016-06-22 09:21:58 +02:00
commit 24e08e9657
2 changed files with 44 additions and 3 deletions

View File

@ -23,10 +23,12 @@ use Symfony\Component\VarDumper\Dumper\HtmlDumper;
class DumpExtension extends \Twig_Extension
{
private $cloner;
private $dumper;
public function __construct(ClonerInterface $cloner)
public function __construct(ClonerInterface $cloner, HtmlDumper $dumper = null)
{
$this->cloner = $cloner;
$this->dumper = $dumper ?: new HtmlDumper();
}
public function getFunctions()
@ -67,11 +69,14 @@ class DumpExtension extends \Twig_Extension
}
$dump = fopen('php://memory', 'r+b');
$dumper = new HtmlDumper($dump);
$prevOutput = $this->dumper->setOutput($dump);
foreach ($vars as $value) {
$dumper->dump($this->cloner->cloneVar($value));
$this->dumper->dump($this->cloner->cloneVar($value));
}
$this->dumper->setOutput($prevOutput);
rewind($dump);
return stream_get_contents($dump);

View File

@ -12,6 +12,7 @@
namespace Symfony\Bridge\Twig\Tests\Extension;
use Symfony\Bridge\Twig\Extension\DumpExtension;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\VarDumper;
use Symfony\Component\VarDumper\Cloner\VarCloner;
@ -103,4 +104,39 @@ class DumpExtensionTest extends \PHPUnit_Framework_TestCase
),
);
}
public function testCustomDumper()
{
$output = '';
$lineDumper = function ($line) use (&$output) {
$output .= $line;
};
$dumper = new HtmlDumper($lineDumper);
$dumper->setDumpHeader('');
$dumper->setDumpBoundaries(
'<pre class=sf-dump-test id=%s data-indent-pad="%s">',
'</pre><script>Sfdump("%s")</script>'
);
$extension = new DumpExtension(new VarCloner(), $dumper);
$twig = new \Twig_Environment($this->getMock('Twig_LoaderInterface'), array(
'debug' => true,
'cache' => false,
'optimizations' => 0,
));
$dump = $extension->dump($twig, array(), 'foo');
$dump = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump);
$this->assertEquals(
'<pre class=sf-dump-test id=sf-dump data-indent-pad=" ">"'.
"<span class=sf-dump-str title=\"3 characters\">foo</span>\"\n".
"</pre><script>Sfdump(\"sf-dump\")</script>\n",
$dump,
'Custom dumper should be used to dump data.'
);
$this->assertEmpty($output, 'Dumper output should be ignored.');
}
}