Last active
September 25, 2017 09:56
-
-
Save merk/1603421 to your computer and use it in GitHub Desktop.
Debug helpers for Symfony2/Twig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
when using Twig 1.5 (which comes by default with Symfony2 now), you should use the new
Twig_Extension_Debug
class instead