Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Theme / TwigEnvironmentTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Theme;
4
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;
12
13 /**
14  * Tests the twig environment.
15  *
16  * @see \Drupal\Core\Template\TwigEnvironment
17  * @group Twig
18  */
19 class TwigEnvironmentTest extends KernelTestBase {
20
21   /**
22    * Modules to enable.
23    *
24    * @var array
25    */
26   public static $modules = ['system'];
27
28   /**
29    * Tests inline templates.
30    */
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');
38
39     $element = [];
40     $unsafe_string = '<script>alert(\'Danger! High voltage!\');</script>';
41     $element['test'] = [
42       '#type' => 'inline_template',
43       '#template' => 'test-with-context <label>{{ unsafe_content }}</label>',
44       '#context' => ['unsafe_content' => $unsafe_string],
45     ];
46     $this->assertEqual($renderer->renderRoot($element), 'test-with-context <label>' . Html::escape($unsafe_string) . '</label>');
47
48     // Enable twig_auto_reload and twig_debug.
49     $settings = Settings::getAll();
50     $settings['twig_debug'] = TRUE;
51     $settings['twig_auto_reload'] = TRUE;
52
53     new Settings($settings);
54     $this->container = \Drupal::service('kernel')->rebuildContainer();
55     \Drupal::setContainer($this->container);
56
57     $element = [];
58     $element['test'] = [
59       '#type' => 'inline_template',
60       '#template' => 'test-with-context {{ llama }}',
61       '#context' => ['llama' => 'muuh'],
62     ];
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');
67
68     // Tests caching of inline templates with long content to ensure the
69     // generated cache key can be used as a filename.
70     $element = [];
71     $element['test'] = [
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 }}.',
74       '#context' => [
75         'llama' => 'necks',
76         'kitten' => 'meow',
77         'flamingo' => 'pink',
78         'panda' => 'bears',
79         'giraffe' => 'leaves',
80       ],
81     ];
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;
84
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);
88
89     $name = '{# inline_template_start #}' . $element['test']['#template'];
90     $prefix = $environment->getTwigCachePrefix();
91
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));
96   }
97
98   /**
99    * Tests that exceptions are thrown when a template is not found.
100    */
101   public function testTemplateNotFoundException() {
102     /** @var \Drupal\Core\Template\TwigEnvironment $environment */
103     $environment = \Drupal::service('twig');
104
105     try {
106       $environment->loadTemplate('this-template-does-not-exist.html.twig')->render([]);
107       $this->fail('Did not throw an exception as expected.');
108     }
109     catch (\Twig_Error_Loader $e) {
110       $this->assertTrue(strpos($e->getMessage(), 'Template "this-template-does-not-exist.html.twig" is not defined') === 0);
111     }
112   }
113
114   /**
115    * Ensures that templates resolve to the same class name and cache file.
116    */
117   public function testTemplateClassname() {
118     /** @var \Drupal\Core\Template\TwigEnvironment $environment */
119     $environment = \Drupal::service('twig');
120
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);
125
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);
130
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);
135
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);
141   }
142
143   /**
144    * Ensures that cacheFilename() varies by extensions + deployment identifier.
145    */
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
149     // static cache.
150     $environment = \Drupal::service('twig');
151
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));
165
166     $original_filename = $environment->getCacheFilename('core/modules/system/templates/container.html.twig');
167     \Drupal::getContainer()->set('twig', NULL);
168
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);
173
174     $this->assertNotEqual($new_extension_filename, $original_filename);
175   }
176
177   /**
178    * {@inheritdoc}
179    */
180   public function register(ContainerBuilder $container) {
181     parent::register($container);
182
183     $container->setDefinition('twig_loader__file_system', new Definition('Twig_Loader_Filesystem', [[sys_get_temp_dir()]]))
184       ->addTag('twig.loader');
185   }
186
187   /**
188    * Test template invalidation.
189    */
190   public function testTemplateInvalidation() {
191     $template_before = <<<TWIG
192 <div>Hello before</div>
193 TWIG;
194     $template_after = <<<TWIG
195 <div>Hello after</div>
196 TWIG;
197
198     $tempfile = tempnam(sys_get_temp_dir(), '__METHOD__') . '.html.twig';
199     file_put_contents($tempfile, $template_before);
200
201     /** @var \Drupal\Core\Template\TwigEnvironment $environment */
202     $environment = \Drupal::service('twig');
203
204     $output = $environment->load(basename($tempfile))->render();
205     $this->assertEquals($template_before, $output);
206
207     file_put_contents($tempfile, $template_after);
208     $output = $environment->load(basename($tempfile))->render();
209     $this->assertEquals($template_before, $output);
210
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');
219
220     $output = $environment->load(basename($tempfile))->render();
221     $this->assertEquals($template_after, $output);
222   }
223
224 }