3 namespace Drupal\KernelTests\Core\Theme;
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Core\DependencyInjection\ContainerBuilder;
8 use Drupal\Core\Site\Settings;
9 use Drupal\Core\Template\TwigPhpStorageCache;
10 use Drupal\KernelTests\KernelTestBase;
11 use Symfony\Component\DependencyInjection\Definition;
14 * Tests the twig environment.
16 * @see \Drupal\Core\Template\TwigEnvironment
19 class TwigEnvironmentTest extends KernelTestBase {
26 public static $modules = ['system'];
29 * Tests inline templates.
31 public function testInlineTemplate() {
32 /** @var \Drupal\Core\Render\RendererInterface $renderer */
33 $renderer = $this->container->get('renderer');
34 /** @var \Drupal\Core\Template\TwigEnvironment $environment */
35 $environment = \Drupal::service('twig');
36 $this->assertEqual($environment->renderInline('test-no-context'), 'test-no-context');
37 $this->assertEqual($environment->renderInline('test-with-context {{ llama }}', ['llama' => 'muuh']), 'test-with-context muuh');
40 $unsafe_string = '<script>alert(\'Danger! High voltage!\');</script>';
42 '#type' => 'inline_template',
43 '#template' => 'test-with-context <label>{{ unsafe_content }}</label>',
44 '#context' => ['unsafe_content' => $unsafe_string],
46 $this->assertEqual($renderer->renderRoot($element), 'test-with-context <label>' . Html::escape($unsafe_string) . '</label>');
48 // Enable twig_auto_reload and twig_debug.
49 $settings = Settings::getAll();
50 $settings['twig_debug'] = TRUE;
51 $settings['twig_auto_reload'] = TRUE;
53 new Settings($settings);
54 $this->container = \Drupal::service('kernel')->rebuildContainer();
55 \Drupal::setContainer($this->container);
59 '#type' => 'inline_template',
60 '#template' => 'test-with-context {{ llama }}',
61 '#context' => ['llama' => 'muuh'],
63 $element_copy = $element;
64 // Render it twice so that twig caching is triggered.
65 $this->assertEqual($renderer->renderRoot($element), 'test-with-context muuh');
66 $this->assertEqual($renderer->renderRoot($element_copy), 'test-with-context muuh');
68 // Tests caching of inline templates with long content to ensure the
69 // generated cache key can be used as a filename.
72 '#type' => 'inline_template',
73 '#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 }}.',
79 'giraffe' => 'leaves',
82 $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.';
83 $element_copy = $element;
85 // Render it twice so that twig caching is triggered.
86 $this->assertEqual($renderer->renderRoot($element), $expected);
87 $this->assertEqual($renderer->renderRoot($element_copy), $expected);
89 $name = '{# inline_template_start #}' . $element['test']['#template'];
90 $prefix = $environment->getTwigCachePrefix();
92 $cache = $environment->getCache();
93 $class = $environment->getTemplateClass($name);
94 $expected = $prefix . '_inline-template_' . substr(Crypt::hashBase64($class), 0, TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH);
95 $this->assertEqual($expected, $cache->generateKey($name, $class));
99 * Tests that exceptions are thrown when a template is not found.
101 public function testTemplateNotFoundException() {
102 /** @var \Drupal\Core\Template\TwigEnvironment $environment */
103 $environment = \Drupal::service('twig');
106 $environment->loadTemplate('this-template-does-not-exist.html.twig')->render([]);
107 $this->fail('Did not throw an exception as expected.');
109 catch (\Twig_Error_Loader $e) {
110 $this->assertTrue(strpos($e->getMessage(), 'Template "this-template-does-not-exist.html.twig" is not defined') === 0);
115 * Ensures that templates resolve to the same class name and cache file.
117 public function testTemplateClassname() {
118 /** @var \Drupal\Core\Template\TwigEnvironment $environment */
119 $environment = \Drupal::service('twig');
121 // Test using an include template path.
122 $name_include = 'container.html.twig';
123 $class_include = $environment->getTemplateClass($name_include);
124 $key_include = $environment->getCache()->generateKey($name_include, $class_include);
126 // Test using a namespaced template path.
127 $name_namespaced = '@system/container.html.twig';
128 $class_namespaced = $environment->getTemplateClass($name_namespaced);
129 $key_namespaced = $environment->getCache()->generateKey($name_namespaced, $class_namespaced);
131 // Test using a direct filesystem template path.
132 $name_direct = 'core/modules/system/templates/container.html.twig';
133 $class_direct = $environment->getTemplateClass($name_direct);
134 $key_direct = $environment->getCache()->generateKey($name_direct, $class_direct);
136 // All three should be equal for both cases.
137 $this->assertEqual($class_include, $class_namespaced);
138 $this->assertEqual($class_namespaced, $class_direct);
139 $this->assertEqual($key_include, $key_namespaced);
140 $this->assertEqual($key_namespaced, $key_direct);
144 * Ensures that cacheFilename() varies by extensions + deployment identifier.
146 public function testCacheFilename() {
147 /** @var \Drupal\Core\Template\TwigEnvironment $environment */
148 // Note: Later we refetch the twig service in order to bypass its internal
150 $environment = \Drupal::service('twig');
152 // A template basename greater than the constant
153 // TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH should get truncated.
154 $cache = $environment->getCache();
155 $long_name = 'core/modules/system/templates/block--system-messages-block.html.twig';
156 $this->assertGreaterThan(TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH, strlen(basename($long_name)));
157 $class = $environment->getTemplateClass($long_name);
158 $key = $cache->generateKey($long_name, $class);
159 $prefix = $environment->getTwigCachePrefix();
160 // The key should consist of the prefix, an underscore, and two strings
161 // each truncated to length TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH
162 // separated by an underscore.
163 $expected = strlen($prefix) + 2 + 2 * TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH;
164 $this->assertEquals($expected, strlen($key));
166 $original_filename = $environment->getCacheFilename('core/modules/system/templates/container.html.twig');
167 \Drupal::getContainer()->set('twig', NULL);
169 \Drupal::service('module_installer')->install(['twig_extension_test']);
170 $environment = \Drupal::service('twig');
171 $new_extension_filename = $environment->getCacheFilename('core/modules/system/templates/container.html.twig');
172 \Drupal::getContainer()->set('twig', NULL);
174 $this->assertNotEqual($new_extension_filename, $original_filename);
180 public function register(ContainerBuilder $container) {
181 parent::register($container);
183 $container->setDefinition('twig_loader__file_system', new Definition('Twig_Loader_Filesystem', [[sys_get_temp_dir()]]))
184 ->addTag('twig.loader');
188 * Test template invalidation.
190 public function testTemplateInvalidation() {
191 $template_before = <<<TWIG
192 <div>Hello before</div>
194 $template_after = <<<TWIG
195 <div>Hello after</div>
198 $tempfile = tempnam(sys_get_temp_dir(), '__METHOD__') . '.html.twig';
199 file_put_contents($tempfile, $template_before);
201 /** @var \Drupal\Core\Template\TwigEnvironment $environment */
202 $environment = \Drupal::service('twig');
204 $output = $environment->load(basename($tempfile))->render();
205 $this->assertEquals($template_before, $output);
207 file_put_contents($tempfile, $template_after);
208 $output = $environment->load(basename($tempfile))->render();
209 $this->assertEquals($template_before, $output);
211 $environment->invalidate();
212 // Manually change $templateClassPrefix to force a different template
213 // classname, as the other class is still loaded. This wouldn't be a problem
214 // on a real site where you reload the page.
215 $reflection = new \ReflectionClass($environment);
216 $property_reflection = $reflection->getProperty('templateClassPrefix');
217 $property_reflection->setAccessible(TRUE);
218 $property_reflection->setValue($environment, 'otherPrefix');
220 $output = $environment->load(basename($tempfile))->render();
221 $this->assertEquals($template_after, $output);