Commit 8dc277d7 authored by willzyx's avatar willzyx

Issue #2725395 by willzyx: Dumper system Part II: Add basic Twig debug support

parent ae6d4158
......@@ -18,3 +18,9 @@ services:
arguments: ['@entity_type.manager']
tags:
- { name: event_subscriber }
devel.twig.debug_extension:
class: Drupal\devel\Twig\Extension\Debug
arguments: ['@devel.dumper']
tags:
- { name: twig.extension }
<?php
namespace Drupal\devel\Twig\Extension;
use Drupal\devel\DevelDumperManagerInterface;
/**
* Provides the Devel debugging function within Twig templates.
*
* NOTE: This extension doesn't do anything unless twig_debug is enabled.
* The twig_debug setting is read from the Twig environment, not Drupal
* Settings, so a container rebuild is necessary when toggling twig_debug on
* and off.
*/
class Debug extends \Twig_Extension {
/**
* The devel dumper service.
*
* @var \Drupal\devel\DevelDumperManagerInterface
*/
protected $dumper;
/**
* Constructs a Debug object.
*
* @param \Drupal\devel\DevelDumperManagerInterface $dumper
* The devel dumper service.
*/
public function __construct(DevelDumperManagerInterface $dumper) {
$this->dumper = $dumper;
}
/**
* {@inheritdoc}
*/
public function getName() {
return 'devel_debug';
}
/**
* {@inheritdoc}
*/
public function getFunctions() {
$functions = [];
foreach (['devel_dump', 'kpr'] as $function) {
$functions[] = new \Twig_SimpleFunction($function, [$this, 'dump'], [
'is_safe' => ['html'],
'needs_environment' => TRUE,
'needs_context' => TRUE,
'is_variadic' => TRUE,
]);
}
foreach (['devel_message', 'dpm', 'dsm'] as $function) {
$functions[] = new \Twig_SimpleFunction($function, [$this, 'message'], [
'is_safe' => ['html'],
'needs_environment' => TRUE,
'needs_context' => TRUE,
'is_variadic' => TRUE,
]);
}
return $functions;
}
/**
* Provides debug function to Twig templates.
*
* Handles 0, 1, or multiple arguments.
*
* @param \Twig_Environment $env
* The twig environment instance.
* @param array $context
* An array of parameters passed to the template.
* @param array $args
* An array of parameters passed the function.
*
* @return string
* String representation of the input variables.
*
* @see \Drupal\devel\DevelDumperManager::dump()
*/
public function dump(\Twig_Environment $env, array $context, array $args = []) {
if (!$env->isDebug()) {
return;
}
ob_start();
// No arguments passed, display full Twig context.
if (empty($args)) {
$context_variables = $this->getContextVariables($context);
$this->dumper->dump($context_variables, 'Twig context');
}
else {
foreach ($args as $variable) {
$this->dumper->dump($variable);
}
}
return ob_get_clean();
}
/**
* Provides debug function to Twig templates.
*
* Handles 0, 1, or multiple arguments.
*
* @param \Twig_Environment $env
* The twig environment instance.
* @param array $context
* An array of parameters passed to the template.
* @param array $args
* An array of parameters passed the function.
*
* @return void
*
* @see \Drupal\devel\DevelDumperManager::message()
*/
public function message(\Twig_Environment $env, array $context, array $args = []) {
if (!$env->isDebug()) {
return;
}
// No arguments passed, display full Twig context.
if (empty($args)) {
$context_variables = $this->getContextVariables($context);
$this->dumper->message($context_variables, 'Twig context');
}
else {
foreach ($args as $variable) {
$this->dumper->message($variable);
}
}
}
/**
* Filters the Twig context variable.
*
* @param array $context
* The Twig context.
*
* @return array
* An array Twig context variables.
*/
protected function getContextVariables(array $context) {
$context_variables = [];
foreach ($context as $key => $value) {
if (!$value instanceof \Twig_Template) {
$context_variables[$key] = $value;
}
}
return $context_variables;
}
}
<?php
namespace Drupal\Tests\devel\Kernel;
/**
* Provides a class for checking dumper output.
*/
trait DevelDumperTestTrait {
/**
* Asserts that the string passed in input is equals to the string
* representation of a variable obtained exporting the data.
*
* Use \Drupal\devel\DevelDumperManager::export().
*
* @param $dump
* The string that contains the dump output to test.
* @param $data
* The variable to dump.
* @param null $name
* (optional) The label to output before variable, defaults to NULL.
* @param string $message
* (optional) A message to display with the assertion.
*/
public function assertDumpExportEquals($dump, $data, $name = NULL, $message = '') {
$output = $this->getDumperExportDump($data, $name);
$this->assertEqual(rtrim($dump), $output, $message);
}
/**
* Asserts that a haystack contains the dump export output.
*
* Use \Drupal\devel\DevelDumperManager::export().
*
* @param $haystack
* The string that contains the dump output to test.
* @param $data
* The variable to dump.
* @param null $name
* (optional) The label to output before variable, defaults to NULL.
* @param string $message
* (optional) A message to display with the assertion.
*/
public function assertContainsDumpExport($haystack, $data, $name = NULL, $message = '') {
$output = $this->getDumperExportDump($data, $name);
$this->assertContains($output, (string) $haystack, $message);
}
/**
* Asserts that the string passed in input is equals to the string
* representation of a variable obtained dumping the data.
*
* Use \Drupal\devel\DevelDumperManager::dump().
*
* @param $dump
* The string that contains the dump output to test.
* @param $data
* The variable to dump.
* @param null $name
* (optional) The label to output before variable, defaults to NULL.
* @param string $message
* (optional) A message to display with the assertion.
*/
public function assertDumpEquals($dump, $data, $name = NULL, $message = '') {
$output = $this->getDumperDump($data, $name);
$this->assertEqual(rtrim($dump), $output, $message);
}
/**
* Asserts that a haystack contains the dump output.
*
* Use \Drupal\devel\DevelDumperManager::dump().
*
* @param $haystack
* The string that contains the dump output to test.
* @param $data
* The variable to dump.
* @param null $name
* (optional) The label to output before variable, defaults to NULL.
* @param string $message
* (optional) A message to display with the assertion.
*/
public function assertContainsDump($haystack, $data, $name = NULL, $message = '') {
$output = $this->getDumperDump($data, $name);
$this->assertContains($output, (string) $haystack, $message);
}
/**
* Returns a string representation of a variable.
*
* @param mixed $input
* The variable to dump.
* @param string $name
* (optional) The label to output before variable, defaults to NULL.
*
* @return string
* String representation of a variable.
*
* @see \Drupal\devel\DevelDumperManager::export()
*/
private function getDumperExportDump($input, $name = NULL) {
$output = \Drupal::service('devel.dumper')->export($input, $name);
return rtrim($output);
}
/**
* Returns a string representation of a variable.
*
* @param mixed $input
* The variable to dump.
* @param string $name
* (optional) The label to output before variable, defaults to NULL.
*
* @return string
* String representation of a variable.
*
* @see \Drupal\devel\DevelDumperManager::dump()
*/
private function getDumperDump($input, $name = NULL) {
ob_start();
\Drupal::service('devel.dumper')->dump($input, $name);
$output = ob_get_contents();
ob_end_clean();
return rtrim($output);
}
}
<?php
namespace Drupal\Tests\devel\Kernel;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\KernelTests\KernelTestBase;
use Drupal\devel\Twig\Extension\Debug;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
/**
* Tests Twig extensions.
*
* @group devel
*/
class DevelTwigExtensionTest extends KernelTestBase {
use DevelDumperTestTrait;
/**
* The user used in test.
*
* @var \Drupal\user\UserInterface
*/
protected $develUser;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['devel', 'user', 'system'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->installSchema('system', 'sequences');
$devel_role = Role::create([
'id' => 'admin',
'permissions' => ['access devel information'],
]);
$devel_role->save();
$this->develUser = User::create([
'name' => $this->randomMachineName(),
'roles' => [$devel_role->id()],
]);
$this->develUser->save();
}
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
parent::register($container);
$parameters = $container->getParameter('twig.config');
$parameters['debug'] = TRUE;
$container->setParameter('twig.config', $parameters);
}
/**
* Tests that Twig extension loads appropriately.
*/
function testTwigExtensionLoaded() {
$twig_service = \Drupal::service('twig');
$extension = $twig_service->getExtension('devel_debug');
$this->assertEquals(get_class($extension), Debug::class, 'Debug Extension loaded successfully.');
}
/**
* Tests that theTwig functions are registered properly.
*/
function testTwigExtensionFunctionsRegistered() {
/** @var \Twig_SimpleFunction[] $functions */
$functions = \Drupal::service('twig')->getFunctions();
$dump_functions = ['devel_dump', 'kpr'];
$message_functions = ['devel_message', 'dpm', 'dsm'];
$registered_functions = $dump_functions + $message_functions;
foreach ($registered_functions as $name) {
$function = $functions[$name];
$this->assertTrue($function instanceof \Twig_SimpleFunction);
$this->assertEquals($function->getName(), $name);
$this->assertTrue($function->needsContext());
$this->assertTrue($function->needsEnvironment());
$this->assertTrue($function->isVariadic());
is_callable($function->getCallable(), TRUE, $callable);
if (in_array($name, $dump_functions)) {
$this->assertEquals($callable, 'Drupal\devel\Twig\Extension\Debug::dump');
}
else {
$this->assertEquals($callable, 'Drupal\devel\Twig\Extension\Debug::message');
}
}
}
/**
* Tests that the Twig extension's function produces expected output.
*/
function testTwigExtensionFunctions() {
$template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_dump() }}';
$expected_template_output = 'test-with-context context! first value second value';
$context = [
'twig_string' => 'context!',
'twig_array' => [
'first' => 'first value',
'second' => 'second value',
],
'twig_object' => new \stdClass(),
];
/** @var \Drupal\Core\Template\TwigEnvironment $environment */
$environment = \Drupal::service('twig');
// Ensures that the twig extension does nothing if the current
// user has not the adequate permission.
$this->assertTrue($environment->isDebug());
$this->assertEquals($environment->renderInline($template, $context), $expected_template_output);
\Drupal::currentUser()->setAccount($this->develUser);
// Ensures that if no argument is passed to the function the twig context is
// dumped.
$output = (string) $environment->renderInline($template, $context);
$this->assertContains($expected_template_output, $output);
$this->assertContainsDump($output, $context, 'Twig context');
// Ensures that if an argument is passed to the function it is dumped.
$template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_dump(twig_array) }}';
$output = (string) $environment->renderInline($template, $context);
$this->assertContains($expected_template_output, $output);
$this->assertContainsDump($output, $context['twig_array']);
// Ensures that if more than one argument is passed the function works
// properly and every argument is dumped separately.
$template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_dump(twig_string, twig_array.first, twig_array, twig_object) }}';
$output = (string) $environment->renderInline($template, $context);
$this->assertContains($expected_template_output, $output);
$this->assertContainsDump($output, $context['twig_string']);
$this->assertContainsDump($output, $context['twig_array']['first']);
$this->assertContainsDump($output, $context['twig_array']);
$this->assertContainsDump($output, $context['twig_object']);
// Clear messages.
drupal_get_messages();
$retrieve_message = function ($messages, $index) {
return isset($messages['status'][$index]) ? (string) $messages['status'][$index] : NULL;
};
// Ensures that if no argument is passed to the function the twig context is
// dumped.
$template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_message() }}';
$output = (string) $environment->renderInline($template, $context);
$this->assertContains($expected_template_output, $output);
$messages = drupal_get_messages();
$this->assertDumpExportEquals($retrieve_message($messages, 0), $context, 'Twig context');
// Ensures that if an argument is passed to the function it is dumped.
$template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_message(twig_array) }}';
$output = (string) $environment->renderInline($template, $context);
$this->assertContains($expected_template_output, $output);
$messages = drupal_get_messages();
$this->assertDumpExportEquals($retrieve_message($messages, 0), $context['twig_array']);
// Ensures that if more than one argument is passed to the function works
// properly and every argument is dumped separately.
$template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_message(twig_string, twig_array.first, twig_array, twig_object) }}';
$output = (string) $environment->renderInline($template, $context);
$this->assertContains($expected_template_output, $output);
$messages = drupal_get_messages();
$this->assertDumpExportEquals($retrieve_message($messages, 0), $context['twig_string']);
$this->assertDumpExportEquals($retrieve_message($messages, 1), $context['twig_array']['first']);
$this->assertDumpExportEquals($retrieve_message($messages, 2), $context['twig_array']);
$this->assertDumpExportEquals($retrieve_message($messages, 3), $context['twig_object']);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment