TwigEnvironmentTest.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. <?php
  2. namespace Drupal\KernelTests\Core\Theme;
  3. use Drupal\Component\Utility\Crypt;
  4. use Drupal\Component\Utility\Html;
  5. use Drupal\Core\Site\Settings;
  6. use Drupal\Core\Template\TwigPhpStorageCache;
  7. use Drupal\KernelTests\KernelTestBase;
  8. /**
  9. * Tests the twig environment.
  10. *
  11. * @see \Drupal\Core\Template\TwigEnvironment
  12. * @group Twig
  13. */
  14. class TwigEnvironmentTest extends KernelTestBase {
  15. /**
  16. * Modules to enable.
  17. *
  18. * @var array
  19. */
  20. public static $modules = ['system'];
  21. /**
  22. * Tests inline templates.
  23. */
  24. public function testInlineTemplate() {
  25. /** @var \Drupal\Core\Render\RendererInterface $renderer */
  26. $renderer = $this->container->get('renderer');
  27. /** @var \Drupal\Core\Template\TwigEnvironment $environment */
  28. $environment = \Drupal::service('twig');
  29. $this->assertEqual($environment->renderInline('test-no-context'), 'test-no-context');
  30. $this->assertEqual($environment->renderInline('test-with-context {{ llama }}', ['llama' => 'muuh']), 'test-with-context muuh');
  31. $element = [];
  32. $unsafe_string = '<script>alert(\'Danger! High voltage!\');</script>';
  33. $element['test'] = [
  34. '#type' => 'inline_template',
  35. '#template' => 'test-with-context <label>{{ unsafe_content }}</label>',
  36. '#context' => ['unsafe_content' => $unsafe_string],
  37. ];
  38. $this->assertEqual($renderer->renderRoot($element), 'test-with-context <label>' . Html::escape($unsafe_string) . '</label>');
  39. // Enable twig_auto_reload and twig_debug.
  40. $settings = Settings::getAll();
  41. $settings['twig_debug'] = TRUE;
  42. $settings['twig_auto_reload'] = TRUE;
  43. new Settings($settings);
  44. $this->container = \Drupal::service('kernel')->rebuildContainer();
  45. \Drupal::setContainer($this->container);
  46. $element = [];
  47. $element['test'] = [
  48. '#type' => 'inline_template',
  49. '#template' => 'test-with-context {{ llama }}',
  50. '#context' => ['llama' => 'muuh'],
  51. ];
  52. $element_copy = $element;
  53. // Render it twice so that twig caching is triggered.
  54. $this->assertEqual($renderer->renderRoot($element), 'test-with-context muuh');
  55. $this->assertEqual($renderer->renderRoot($element_copy), 'test-with-context muuh');
  56. // Tests caching of inline templates with long content to ensure the
  57. // generated cache key can be used as a filename.
  58. $element = [];
  59. $element['test'] = [
  60. '#type' => 'inline_template',
  61. '#template' => 'Llamas sometimes spit and wrestle with their {{ llama }}. Kittens are soft and fuzzy and they sometimes say {{ kitten }}. Flamingos have long legs and they are usually {{ flamingo }}. Pandas eat bamboo and they are {{ panda }}. Giraffes have long necks and long tongues and they eat {{ giraffe }}.',
  62. '#context' => [
  63. 'llama' => 'necks',
  64. 'kitten' => 'meow',
  65. 'flamingo' => 'pink',
  66. 'panda' => 'bears',
  67. 'giraffe' => 'leaves',
  68. ],
  69. ];
  70. $expected = 'Llamas sometimes spit and wrestle with their necks. Kittens are soft and fuzzy and they sometimes say meow. Flamingos have long legs and they are usually pink. Pandas eat bamboo and they are bears. Giraffes have long necks and long tongues and they eat leaves.';
  71. $element_copy = $element;
  72. // Render it twice so that twig caching is triggered.
  73. $this->assertEqual($renderer->renderRoot($element), $expected);
  74. $this->assertEqual($renderer->renderRoot($element_copy), $expected);
  75. $name = '{# inline_template_start #}' . $element['test']['#template'];
  76. $prefix = $environment->getTwigCachePrefix();
  77. $cache = $environment->getCache();
  78. $class = $environment->getTemplateClass($name);
  79. $expected = $prefix . '_inline-template_' . substr(Crypt::hashBase64($class), 0, TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH);
  80. $this->assertEqual($expected, $cache->generateKey($name, $class));
  81. }
  82. /**
  83. * Tests that exceptions are thrown when a template is not found.
  84. */
  85. public function testTemplateNotFoundException() {
  86. /** @var \Drupal\Core\Template\TwigEnvironment $environment */
  87. $environment = \Drupal::service('twig');
  88. try {
  89. $environment->loadTemplate('this-template-does-not-exist.html.twig')->render([]);
  90. $this->fail('Did not throw an exception as expected.');
  91. }
  92. catch (\Twig_Error_Loader $e) {
  93. $this->assertTrue(strpos($e->getMessage(), 'Template "this-template-does-not-exist.html.twig" is not defined') === 0);
  94. }
  95. }
  96. /**
  97. * Ensures that cacheFilename() varies by extensions + deployment identifier.
  98. */
  99. public function testCacheFilename() {
  100. /** @var \Drupal\Core\Template\TwigEnvironment $environment */
  101. // Note: Later we refetch the twig service in order to bypass its internal
  102. // static cache.
  103. $environment = \Drupal::service('twig');
  104. // A template basename greater than the constant
  105. // TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH should get truncated.
  106. $cache = $environment->getCache();
  107. $long_name = 'core/modules/system/templates/block--system-messages-block.html.twig';
  108. $this->assertGreaterThan(TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH, strlen(basename($long_name)));
  109. $class = $environment->getTemplateClass($long_name);
  110. $key = $cache->generateKey($long_name, $class);
  111. $prefix = $environment->getTwigCachePrefix();
  112. // The key should consist of the prefix, an underscore, and two strings
  113. // each truncated to length TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH
  114. // separated by an underscore.
  115. $expected = strlen($prefix) + 2 + 2 * TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH;
  116. $this->assertEquals($expected, strlen($key));
  117. $original_filename = $environment->getCacheFilename('core/modules/system/templates/container.html.twig');
  118. \Drupal::getContainer()->set('twig', NULL);
  119. \Drupal::service('module_installer')->install(['twig_extension_test']);
  120. $environment = \Drupal::service('twig');
  121. $new_extension_filename = $environment->getCacheFilename('core/modules/system/templates/container.html.twig');
  122. \Drupal::getContainer()->set('twig', NULL);
  123. $this->assertNotEqual($new_extension_filename, $original_filename);
  124. }
  125. }