public function KintExtension::kint in Devel 8.2
Same name and namespace in other branches
- 8 kint/src/Twig/KintExtension.php \Drupal\kint\Twig\KintExtension::kint()
Provides Kint function to Twig templates.
Handles 0, 1, or multiple arguments.
Code derived from https://github.com/barelon/CgKintBundle.
Parameters
\Twig_Environment $env: The twig environment instance.
array $context: An array of parameters passed to the template.
array $args: An array of parameters passed the function.
Return value
string String representation of the input variables.
File
- kint/
src/ Twig/ KintExtension.php, line 48
Class
- KintExtension
- Provides the Kint debugging function within Twig templates.
Namespace
Drupal\kint\TwigCode
public function kint(\Twig_Environment $env, array $context, array $args = []) {
// Don't do anything unless twig_debug is enabled. This reads from the Twig
// environment, not Drupal Settings, so a container rebuild is necessary
// when toggling twig_debug on and off. We can consider injecting Settings.
if (!$env
->isDebug()) {
return;
}
kint_require();
// Don't display where Kint was called from.
// @todo Can we add information about which template Kint was called from?
\Kint::$displayCalledFrom = FALSE;
// No arguments passed to kint(), display full Twig context.
if (empty($args)) {
$kint_variable = array();
foreach ($context as $key => $value) {
if (!$value instanceof \Twig_Template) {
$kint_variable[$key] = $value;
}
}
$result = @\Kint::dump($kint_variable);
$output = str_replace('$kint_variable', 'Twig context', $result);
}
else {
// Try to get the names of variables from the Twig template.
$parameters = $this
->getTwigFunctionParameters();
// If there is only one argument, pass to Kint without too much hassle.
if (count($args) == 1) {
$kint_variable = reset($args);
$variable_name = reset($parameters);
$result = @\Kint::dump($kint_variable);
// Replace $kint_variable with the name of the variable in the Twig
// template.
$output = str_replace('$kint_variable', $variable_name, $result);
}
else {
$kint_args = [];
// Build an array of variable to pass to Kint.
// @todo Can we just call_user_func_array while still retaining the
// variable names?
foreach ($args as $index => $arg) {
// Prepend a unique index to allow debugging the same variable more
// than once in the same Kint dump.
$name = !empty($parameters[$index]) ? $parameters[$index] : $index;
$kint_args['_index_' . $index . '_' . $name] = $arg;
}
$result = @\Kint::dump($kint_args);
// Display a comma separated list of the variables contained in this group.
$output = str_replace('$kint_args', implode(', ', $parameters), $result);
// Remove unique indexes from output.
$output = preg_replace('/_index_([0-9]+)_/', '', $output);
}
}
return $output;
}