Skip to content

Instantly share code, notes, and snippets.

@merk
Last active September 25, 2017 09:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merk/1603421 to your computer and use it in GitHub Desktop.
Save merk/1603421 to your computer and use it in GitHub Desktop.
Debug helpers for Symfony2/Twig
services:
twig.extension.debug:
class: Twig_Extension_Debug
tags:
- { name: twig.extension }
twig.extension.infinite_debug:
class: Infinite\Helper\Twig\Debug
tags:
- { name: twig.extension }
<?php
namespace Infinite\Helper\Twig;
use Doctrine\Common\Util\Debug as DoctrineDebug;
class Debug extends \Twig_Extension
{
/**
* Returns a list of global functions to add to the existing list.
*
* @return array An array of global functions
*/
public function getFunctions()
{
// dump is safe if var_dump is overriden by xdebug
$isDumpOutputHtmlSafe = extension_loaded('xdebug') &&
(
false === get_cfg_var('xdebug.overload_var_dump') ||
get_cfg_var('xdebug.overload_var_dump')
) &&
get_cfg_var('html_errors');
return array(
'doctrine_dump' => new \Twig_Function_Method($this, 'dump', array(
'is_safe' => $isDumpOutputHtmlSafe ? array('html') : array(),
'needs_context' => true,
'needs_environment' => true
)),
'dd' => new \Twig_Function_Method($this, 'dump', array(
'is_safe' => $isDumpOutputHtmlSafe ? array('html') : array(),
'needs_context' => true,
'needs_environment' => true
))
);
}
public function dump(\Twig_Environment $env, $context)
{
// Taken from twig_var_dump();
if (!$env->isDebug()) {
return '';
}
ob_start();
$count = func_num_args();
if (2 === $count) {
$vars = array();
foreach ($context as $key => $value) {
if (!$value instanceof \Twig_Template) {
$vars[$key] = $value;
}
}
DoctrineDebug::dump($vars, 3);
} else {
$depth = ($count > 3 and is_integer(func_get_arg($count - 1))) ? func_get_arg($count - 1) : 3;
for ($i = 2; $i < $count; $i++) {
DoctrineDebug::dump(func_get_arg($i), $depth);
}
}
return ob_get_clean();
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'infinite_debug';
}
}
@stof
Copy link

stof commented Jan 12, 2012

when using Twig 1.5 (which comes by default with Symfony2 now), you should use the new Twig_Extension_Debug class instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment