* * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Twig\Tests\Extension; use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\DumpExtension; use Symfony\Component\VarDumper\Dumper\HtmlDumper; use Symfony\Component\VarDumper\VarDumper; use Symfony\Component\VarDumper\Cloner\VarCloner; use Twig\Environment; use Twig\Loader\ArrayLoader; class DumpExtensionTest extends TestCase { /** * @dataProvider getDumpTags */ public function testDumpTag($template, $debug, $expectedOutput, $expectedDumped) { $extension = new DumpExtension(new VarCloner()); $twig = new Environment(new ArrayLoader(array('template' => $template)), array( 'debug' => $debug, 'cache' => false, 'optimizations' => 0, )); $twig->addExtension($extension); $dumped = null; $exception = null; $prevDumper = VarDumper::setHandler(function ($var) use (&$dumped) { $dumped = $var; }); try { $this->assertEquals($expectedOutput, $twig->render('template')); } catch (\Exception $exception) { } VarDumper::setHandler($prevDumper); if (null !== $exception) { throw $exception; } $this->assertSame($expectedDumped, $dumped); } public function getDumpTags() { return array( array('A{% dump %}B', true, 'AB', array()), array('A{% set foo="bar"%}B{% dump %}C', true, 'ABC', array('foo' => 'bar')), array('A{% dump %}B', false, 'AB', null), ); } /** * @dataProvider getDumpArgs */ public function testDump($context, $args, $expectedOutput, $debug = true) { $extension = new DumpExtension(new VarCloner()); $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array( 'debug' => $debug, 'cache' => false, 'optimizations' => 0, )); array_unshift($args, $context); array_unshift($args, $twig); $dump = call_user_func_array(array($extension, 'dump'), $args); if ($debug) { $this->assertStringStartsWith('\n"), array( array(), array(123, 456), "
123\n
\n" ."
456\n
\n", ), array( array('foo' => 'bar'), array(), "
array:1 [\n"
                ."  \"foo\" => \"bar\"\n"
                ."]\n"
                ."
\n", ), ); } public function testCustomDumper() { $output = ''; $lineDumper = function ($line) use (&$output) { $output .= $line; }; $dumper = new HtmlDumper($lineDumper); $dumper->setDumpHeader(''); $dumper->setDumpBoundaries( '
',
            '
' ); $extension = new DumpExtension(new VarCloner(), $dumper); $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array( 'debug' => true, 'cache' => false, 'optimizations' => 0, )); $dump = $extension->dump($twig, array(), 'foo'); $dump = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump); $this->assertEquals( '
"'.
            "foo\"\n".
            "
\n", $dump, 'Custom dumper should be used to dump data.' ); $this->assertEmpty($output, 'Dumper output should be ignored.'); } }