Security update for Core, with self-updated composer
[yaffs-website] / web / core / tests / Drupal / Tests / Core / Render / RendererTest.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\Tests\Core\Render\RendererTest.
6  */
7
8 namespace Drupal\Tests\Core\Render;
9
10 use Drupal\Component\Render\MarkupInterface;
11 use Drupal\Core\Access\AccessResult;
12 use Drupal\Core\Access\AccessResultInterface;
13 use Drupal\Core\Cache\Cache;
14 use Drupal\Core\Render\Element;
15 use Drupal\Core\Render\Markup;
16 use Drupal\Core\Template\Attribute;
17
18 /**
19  * @coversDefaultClass \Drupal\Core\Render\Renderer
20  * @group Render
21  */
22 class RendererTest extends RendererTestBase {
23
24   protected $defaultThemeVars = [
25     '#cache' => [
26       'contexts' => [
27         'languages:language_interface',
28         'theme',
29       ],
30       'tags' => [],
31       'max-age' => Cache::PERMANENT,
32     ],
33     '#attached' => [],
34     '#children' => '',
35   ];
36
37   /**
38    * @covers ::render
39    * @covers ::doRender
40    *
41    * @dataProvider providerTestRenderBasic
42    */
43   public function testRenderBasic($build, $expected, callable $setup_code = NULL) {
44     if (isset($setup_code)) {
45       $setup_code = $setup_code->bindTo($this);
46       $setup_code();
47     }
48
49     if (isset($build['#markup'])) {
50       $this->assertNotInstanceOf(MarkupInterface::class, $build['#markup'], 'The #markup value is not marked safe before rendering.');
51     }
52     $render_output = $this->renderer->renderRoot($build);
53     $this->assertSame($expected, (string) $render_output);
54     if ($render_output !== '') {
55       $this->assertInstanceOf(MarkupInterface::class, $render_output, 'Output of render is marked safe.');
56       $this->assertInstanceOf(MarkupInterface::class, $build['#markup'], 'The #markup value is marked safe after rendering.');
57     }
58   }
59
60   /**
61    * Provides a list of render arrays to test basic rendering.
62    *
63    * @return array
64    */
65   public function providerTestRenderBasic() {
66     $data = [];
67
68     // Part 1: the most simplistic render arrays possible, none using #theme.
69
70     // Pass a NULL.
71     $data[] = [NULL, ''];
72     // Pass an empty string.
73     $data[] = ['', ''];
74     // Previously printed, see ::renderTwice for a more integration-like test.
75     $data[] = [
76       ['#markup' => 'foo', '#printed' => TRUE],
77       '',
78     ];
79     // Printed in pre_render.
80     $data[] = [
81       [
82         '#markup' => 'foo',
83         '#pre_render' => [[new TestCallables(), 'preRenderPrinted']],
84       ],
85       '',
86     ];
87     // Basic #markup based renderable array.
88     $data[] = [
89       ['#markup' => 'foo'],
90       'foo',
91     ];
92     // Basic #plain_text based renderable array.
93     $data[] = [
94       ['#plain_text' => 'foo'],
95       'foo',
96     ];
97     // Mixing #plain_text and #markup based renderable array.
98     $data[] = [
99       ['#plain_text' => '<em>foo</em>', '#markup' => 'bar'],
100       '&lt;em&gt;foo&lt;/em&gt;',
101     ];
102     // Safe strings in #plain_text are still escaped.
103     $data[] = [
104       ['#plain_text' => Markup::create('<em>foo</em>')],
105       '&lt;em&gt;foo&lt;/em&gt;',
106     ];
107     // Renderable child element.
108     $data[] = [
109       ['child' => ['#markup' => 'bar']],
110       'bar',
111     ];
112     // XSS filtering test.
113     $data[] = [
114       ['child' => ['#markup' => "This is <script>alert('XSS')</script> test"]],
115       "This is alert('XSS') test",
116     ];
117     // XSS filtering test.
118     $data[] = [
119       [
120         'child' => [
121           '#markup' => "This is <script>alert('XSS')</script> test",
122           '#allowed_tags' => ['script'],
123         ],
124       ],
125       "This is <script>alert('XSS')</script> test",
126     ];
127     // XSS filtering test.
128     $data[] = [
129       [
130         'child' => [
131           '#markup' => "This is <script><em>alert('XSS')</em></script> <strong>test</strong>",
132           '#allowed_tags' => ['em', 'strong'],
133         ],
134       ],
135       "This is <em>alert('XSS')</em> <strong>test</strong>",
136     ];
137     // Html escaping test.
138     $data[] = [
139       [
140         'child' => [
141           '#plain_text' => "This is <script><em>alert('XSS')</em></script> <strong>test</strong>",
142         ],
143       ],
144       "This is &lt;script&gt;&lt;em&gt;alert(&#039;XSS&#039;)&lt;/em&gt;&lt;/script&gt; &lt;strong&gt;test&lt;/strong&gt;",
145     ];
146     // XSS filtering by default test.
147     $data[] = [
148       [
149         'child' => [
150           '#markup' => "This is <script><em>alert('XSS')</em></script> <strong>test</strong>",
151         ],
152       ],
153       "This is <em>alert('XSS')</em> <strong>test</strong>",
154     ];
155     // Ensure non-XSS tags are not filtered out.
156     $data[] = [
157       [
158         'child' => [
159           '#markup' => "This is <strong><script>alert('not a giraffe')</script></strong> test",
160         ],
161       ],
162       "This is <strong>alert('not a giraffe')</strong> test",
163     ];
164     // #children set but empty, and renderable children.
165     $data[] = [
166       ['#children' => '', 'child' => ['#markup' => 'bar']],
167       'bar',
168     ];
169     // #children set, not empty, and renderable children. #children will be
170     // assumed oto be the rendered child elements, even though the #markup for
171     // 'child' differs.
172     $data[] = [
173       ['#children' => 'foo', 'child' => ['#markup' => 'bar']],
174       'foo',
175     ];
176     // Ensure that content added to #markup via a #pre_render callback is safe.
177     $data[] = [
178       [
179         '#markup' => 'foo',
180         '#pre_render' => [function ($elements) {
181           $elements['#markup'] .= '<script>alert("bar");</script>';
182           return $elements;
183         }
184         ],
185       ],
186       'fooalert("bar");',
187     ];
188     // Test #allowed_tags in combination with #markup and #pre_render.
189     $data[] = [
190       [
191         '#markup' => 'foo',
192         '#allowed_tags' => ['script'],
193         '#pre_render' => [function ($elements) {
194           $elements['#markup'] .= '<script>alert("bar");</script>';
195           return $elements;
196         }
197         ],
198       ],
199       'foo<script>alert("bar");</script>',
200     ];
201     // Ensure output is escaped when adding content to #check_plain through
202     // a #pre_render callback.
203     $data[] = [
204       [
205         '#plain_text' => 'foo',
206         '#pre_render' => [function ($elements) {
207           $elements['#plain_text'] .= '<script>alert("bar");</script>';
208           return $elements;
209         }
210         ],
211       ],
212       'foo&lt;script&gt;alert(&quot;bar&quot;);&lt;/script&gt;',
213     ];
214
215     // Part 2: render arrays using #theme and #theme_wrappers.
216
217     // Tests that #theme and #theme_wrappers can co-exist on an element.
218     $build = [
219       '#theme' => 'common_test_foo',
220       '#foo' => 'foo',
221       '#bar' => 'bar',
222       '#theme_wrappers' => ['container'],
223       '#attributes' => ['class' => ['baz']],
224     ];
225     $setup_code_type_link = function () {
226       $this->setupThemeContainer();
227       $this->themeManager->expects($this->at(0))
228         ->method('render')
229         ->with('common_test_foo', $this->anything())
230         ->willReturnCallback(function ($theme, $vars) {
231           return $vars['#foo'] . $vars['#bar'];
232         });
233     };
234     $data[] = [$build, '<div class="baz">foobar</div>' . "\n", $setup_code_type_link];
235
236     // Tests that #theme_wrappers can disambiguate element attributes shared
237     // with rendering methods that build #children by using the alternate
238     // #theme_wrappers attribute override syntax.
239     $build = [
240       '#type' => 'link',
241       '#theme_wrappers' => [
242         'container' => [
243           '#attributes' => ['class' => ['baz']],
244         ],
245       ],
246       '#attributes' => ['id' => 'foo'],
247       '#url' => 'https://www.drupal.org',
248       '#title' => 'bar',
249     ];
250     $setup_code_type_link = function () {
251       $this->setupThemeContainer();
252       $this->themeManager->expects($this->at(0))
253         ->method('render')
254         ->with('link', $this->anything())
255         ->willReturnCallback(function ($theme, $vars) {
256           $attributes = new Attribute(['href' => $vars['#url']] + (isset($vars['#attributes']) ? $vars['#attributes'] : []));
257           return '<a' . (string) $attributes . '>' . $vars['#title'] . '</a>';
258         });
259     };
260     $data[] = [$build, '<div class="baz"><a href="https://www.drupal.org" id="foo">bar</a></div>' . "\n", $setup_code_type_link];
261
262     // Tests that #theme_wrappers can disambiguate element attributes when the
263     // "base" attribute is not set for #theme.
264     $build = [
265       '#type' => 'link',
266       '#url' => 'https://www.drupal.org',
267       '#title' => 'foo',
268       '#theme_wrappers' => [
269         'container' => [
270           '#attributes' => ['class' => ['baz']],
271         ],
272       ],
273     ];
274     $data[] = [$build, '<div class="baz"><a href="https://www.drupal.org">foo</a></div>' . "\n", $setup_code_type_link];
275
276     // Tests two 'container' #theme_wrappers, one using the "base" attributes
277     // and one using an override.
278     $build = [
279       '#attributes' => ['class' => ['foo']],
280       '#theme_wrappers' => [
281         'container' => [
282           '#attributes' => ['class' => ['bar']],
283         ],
284         'container',
285       ],
286     ];
287     $setup_code = function () {
288       $this->setupThemeContainer($this->any());
289     };
290     $data[] = [$build, '<div class="foo"><div class="bar"></div>' . "\n" . '</div>' . "\n", $setup_code];
291
292     // Tests array syntax theme hook suggestion in #theme_wrappers.
293     $build = [
294       '#theme_wrappers' => [['container']],
295       '#attributes' => ['class' => ['foo']],
296     ];
297     $setup_code = function () {
298       $this->setupThemeContainerMultiSuggestion($this->any());
299     };
300     $data[] = [$build, '<div class="foo"></div>' . "\n", $setup_code];
301
302     // Part 3: render arrays using #markup as a fallback for #theme hooks.
303
304     // Theme suggestion is not implemented, #markup should be rendered.
305     $build = [
306       '#theme' => ['suggestionnotimplemented'],
307       '#markup' => 'foo',
308     ];
309     $setup_code = function () {
310       $this->themeManager->expects($this->once())
311         ->method('render')
312         ->with(['suggestionnotimplemented'], $this->anything())
313         ->willReturn(FALSE);
314     };
315     $data[] = [$build, 'foo', $setup_code];
316
317     // Tests unimplemented theme suggestion, child #markup should be rendered.
318     $build = [
319       '#theme' => ['suggestionnotimplemented'],
320       'child' => [
321         '#markup' => 'foo',
322       ],
323     ];
324     $setup_code = function () {
325       $this->themeManager->expects($this->once())
326         ->method('render')
327         ->with(['suggestionnotimplemented'], $this->anything())
328         ->willReturn(FALSE);
329     };
330     $data[] = [$build, 'foo', $setup_code];
331
332     // Tests implemented theme suggestion: #markup should not be rendered.
333     $build = [
334       '#theme' => ['common_test_empty'],
335       '#markup' => 'foo',
336     ];
337     $theme_function_output = $this->randomContextValue();
338     $setup_code = function () use ($theme_function_output) {
339       $this->themeManager->expects($this->once())
340         ->method('render')
341         ->with(['common_test_empty'], $this->anything())
342         ->willReturn($theme_function_output);
343     };
344     $data[] = [$build, $theme_function_output, $setup_code];
345
346     // Tests implemented theme suggestion: children should not be rendered.
347     $build = [
348       '#theme' => ['common_test_empty'],
349       'child' => [
350         '#markup' => 'foo',
351       ],
352     ];
353     $data[] = [$build, $theme_function_output, $setup_code];
354
355     // Part 4: handling of #children and child renderable elements.
356
357     // #theme is implemented so the values of both #children and 'child' will
358     // be ignored - it is the responsibility of the theme hook to render these
359     // if appropriate.
360     $build = [
361       '#theme' => 'common_test_foo',
362       '#children' => 'baz',
363       'child' => ['#markup' => 'boo'],
364     ];
365     $setup_code = function () {
366       $this->themeManager->expects($this->once())
367         ->method('render')
368         ->with('common_test_foo', $this->anything())
369         ->willReturn('foobar');
370     };
371     $data[] = [$build, 'foobar', $setup_code];
372
373     // #theme is implemented but #render_children is TRUE. As in the case where
374     // #theme is not set, empty #children means child elements are rendered
375     // recursively.
376     $build = [
377       '#theme' => 'common_test_foo',
378       '#children' => '',
379       '#render_children' => TRUE,
380       'child' => [
381         '#markup' => 'boo',
382       ],
383     ];
384     $setup_code = function () {
385       $this->themeManager->expects($this->never())
386         ->method('render');
387     };
388     $data[] = [$build, 'boo', $setup_code];
389
390     // #theme is implemented but #render_children is TRUE. As in the case where
391     // #theme is not set, #children will take precedence over 'child'.
392     $build = [
393       '#theme' => 'common_test_foo',
394       '#children' => 'baz',
395       '#render_children' => TRUE,
396       'child' => [
397         '#markup' => 'boo',
398       ],
399     ];
400     $setup_code = function () {
401       $this->themeManager->expects($this->never())
402         ->method('render');
403     };
404     $data[] = [$build, 'baz', $setup_code];
405
406     // #theme is implemented but #render_children is TRUE. In this case the
407     // calling code is expecting only the children to be rendered. #prefix and
408     // #suffix should not be inherited for the children.
409     $build = [
410       '#theme' => 'common_test_foo',
411       '#children' => '',
412       '#prefix' => 'kangaroo',
413       '#suffix' => 'unicorn',
414       '#render_children' => TRUE,
415       'child' => [
416         '#markup' => 'kitten',
417       ],
418     ];
419     $setup_code = function () {
420       $this->themeManager->expects($this->never())
421         ->method('render');
422     };
423     $data[] = [$build, 'kitten', $setup_code];
424
425     return $data;
426   }
427
428   /**
429    * @covers ::render
430    * @covers ::doRender
431    */
432   public function testRenderSorting() {
433     $first = $this->randomMachineName();
434     $second = $this->randomMachineName();
435     // Build an array with '#weight' set for each element.
436     $elements = [
437       'second' => [
438         '#weight' => 10,
439         '#markup' => $second,
440       ],
441       'first' => [
442         '#weight' => 0,
443         '#markup' => $first,
444       ],
445     ];
446     $output = $this->renderer->renderRoot($elements);
447
448     // The lowest weight element should appear last in $output.
449     $this->assertTrue(strpos($output, $second) > strpos($output, $first), 'Elements were sorted correctly by weight.');
450
451     // Confirm that the $elements array has '#sorted' set to TRUE.
452     $this->assertTrue($elements['#sorted'], "'#sorted' => TRUE was added to the array");
453
454     // Pass $elements through \Drupal\Core\Render\Element::children() and
455     // ensure it remains sorted in the correct order. drupal_render() will
456     // return an empty string if used on the same array in the same request.
457     $children = Element::children($elements);
458     $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
459     $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
460   }
461
462   /**
463    * @covers ::render
464    * @covers ::doRender
465    */
466   public function testRenderSortingWithSetHashSorted() {
467     $first = $this->randomMachineName();
468     $second = $this->randomMachineName();
469     // The same array structure again, but with #sorted set to TRUE.
470     $elements = [
471       'second' => [
472         '#weight' => 10,
473         '#markup' => $second,
474       ],
475       'first' => [
476         '#weight' => 0,
477         '#markup' => $first,
478       ],
479       '#sorted' => TRUE,
480     ];
481     $output = $this->renderer->renderRoot($elements);
482
483     // The elements should appear in output in the same order as the array.
484     $this->assertTrue(strpos($output, $second) < strpos($output, $first), 'Elements were not sorted.');
485   }
486
487   /**
488    * @covers ::render
489    * @covers ::doRender
490    *
491    * @dataProvider providerAccessValues
492    */
493   public function testRenderWithPresetAccess($access) {
494     $build = [
495       '#access' => $access,
496     ];
497
498     $this->assertAccess($build, $access);
499   }
500
501   /**
502    * @covers ::render
503    * @covers ::doRender
504    *
505    * @dataProvider providerAccessValues
506    */
507   public function testRenderWithAccessCallbackCallable($access) {
508     $build = [
509       '#access_callback' => function () use ($access) {
510         return $access;
511       }
512     ];
513
514     $this->assertAccess($build, $access);
515   }
516
517   /**
518    * Ensures that the #access property wins over the callable.
519    *
520    * @covers ::render
521    * @covers ::doRender
522    *
523    * @dataProvider providerAccessValues
524    */
525   public function testRenderWithAccessPropertyAndCallback($access) {
526     $build = [
527       '#access' => $access,
528       '#access_callback' => function () {
529         return TRUE;
530       }
531     ];
532
533     $this->assertAccess($build, $access);
534   }
535
536   /**
537    * @covers ::render
538    * @covers ::doRender
539    *
540    * @dataProvider providerAccessValues
541    */
542   public function testRenderWithAccessControllerResolved($access) {
543
544     switch ($access) {
545       case AccessResult::allowed():
546         $method = 'accessResultAllowed';
547         break;
548
549       case AccessResult::forbidden():
550         $method = 'accessResultForbidden';
551         break;
552
553       case FALSE:
554         $method = 'accessFalse';
555         break;
556
557       case TRUE:
558         $method = 'accessTrue';
559         break;
560     }
561
562     $build = [
563       '#access_callback' => 'Drupal\Tests\Core\Render\TestAccessClass::' . $method,
564     ];
565
566     $this->assertAccess($build, $access);
567   }
568
569   /**
570    * @covers ::render
571    * @covers ::doRender
572    */
573   public function testRenderAccessCacheabilityDependencyInheritance() {
574     $build = [
575       '#access' => AccessResult::allowed()->addCacheContexts(['user']),
576     ];
577
578     $this->renderer->renderPlain($build);
579
580     $this->assertEquals(['languages:language_interface', 'theme', 'user'], $build['#cache']['contexts']);
581   }
582
583   /**
584    * Tests rendering same render array twice.
585    *
586    * Tests that a first render returns the rendered output and a second doesn't
587    * because of the #printed property. Also tests that correct metadata has been
588    * set for re-rendering.
589    *
590    * @covers ::render
591    * @covers ::doRender
592    *
593    * @dataProvider providerRenderTwice
594    */
595   public function testRenderTwice($build) {
596     $this->assertEquals('kittens', $this->renderer->renderRoot($build));
597     $this->assertEquals('kittens', $build['#markup']);
598     $this->assertEquals(['kittens-147'], $build['#cache']['tags']);
599     $this->assertTrue($build['#printed']);
600
601     // We don't want to reprint already printed render arrays.
602     $this->assertEquals('', $this->renderer->renderRoot($build));
603   }
604
605   /**
606    * Provides a list of render array iterations.
607    *
608    * @return array
609    */
610   public function providerRenderTwice() {
611     return [
612       [
613         [
614           '#markup' => 'kittens',
615           '#cache' => [
616             'tags' => ['kittens-147']
617           ],
618         ],
619       ],
620       [
621         [
622           'child' => [
623             '#markup' => 'kittens',
624             '#cache' => [
625               'tags' => ['kittens-147'],
626             ],
627           ],
628         ],
629       ],
630       [
631         [
632           '#render_children' => TRUE,
633           'child' => [
634             '#markup' => 'kittens',
635             '#cache' => [
636               'tags' => ['kittens-147'],
637             ],
638           ],
639         ],
640       ],
641     ];
642   }
643
644   /**
645    * Ensures that #access is taken in account when rendering #render_children.
646    */
647   public function testRenderChildrenAccess() {
648     $build = [
649       '#access' => FALSE,
650       '#render_children' => TRUE,
651       'child' => [
652         '#markup' => 'kittens',
653       ],
654     ];
655
656     $this->assertEquals('', $this->renderer->renderRoot($build));
657   }
658
659   /**
660    * Provides a list of both booleans.
661    *
662    * @return array
663    */
664   public function providerAccessValues() {
665     return [
666       [FALSE],
667       [TRUE],
668       [AccessResult::forbidden()],
669       [AccessResult::allowed()],
670     ];
671   }
672
673   /**
674    * Asserts that a render array with access checking renders correctly.
675    *
676    * @param array $build
677    *   A render array with either #access or #access_callback.
678    * @param bool $access
679    *   Whether the render array is accessible or not.
680    */
681   protected function assertAccess($build, $access) {
682     $sensitive_content = $this->randomContextValue();
683     $build['#markup'] = $sensitive_content;
684     if (($access instanceof AccessResultInterface && $access->isAllowed()) || $access === TRUE) {
685       $this->assertSame($sensitive_content, (string) $this->renderer->renderRoot($build));
686     }
687     else {
688       $this->assertSame('', (string) $this->renderer->renderRoot($build));
689     }
690   }
691
692   protected function setupThemeContainer($matcher = NULL) {
693     $this->themeManager->expects($matcher ?: $this->at(1))
694       ->method('render')
695       ->with('container', $this->anything())
696       ->willReturnCallback(function ($theme, $vars) {
697         return '<div' . (string) (new Attribute($vars['#attributes'])) . '>' . $vars['#children'] . "</div>\n";
698       });
699   }
700
701   protected function setupThemeContainerMultiSuggestion($matcher = NULL) {
702     $this->themeManager->expects($matcher ?: $this->at(1))
703       ->method('render')
704       ->with(['container'], $this->anything())
705       ->willReturnCallback(function ($theme, $vars) {
706         return '<div' . (string) (new Attribute($vars['#attributes'])) . '>' . $vars['#children'] . "</div>\n";
707       });
708   }
709
710   /**
711    * @covers ::render
712    * @covers ::doRender
713    */
714   public function testRenderWithoutThemeArguments() {
715     $element = [
716       '#theme' => 'common_test_foo',
717     ];
718
719     $this->themeManager->expects($this->once())
720       ->method('render')
721       ->with('common_test_foo', $this->defaultThemeVars + $element)
722       ->willReturn('foobar');
723
724     // Test that defaults work.
725     $this->assertEquals($this->renderer->renderRoot($element), 'foobar', 'Defaults work');
726   }
727
728   /**
729    * @covers ::render
730    * @covers ::doRender
731    */
732   public function testRenderWithThemeArguments() {
733     $element = [
734       '#theme' => 'common_test_foo',
735       '#foo' => $this->randomMachineName(),
736       '#bar' => $this->randomMachineName(),
737     ];
738
739     $this->themeManager->expects($this->once())
740       ->method('render')
741       ->with('common_test_foo', $this->defaultThemeVars + $element)
742       ->willReturnCallback(function ($hook, $vars) {
743         return $vars['#foo'] . $vars['#bar'];
744       });
745
746     // Tests that passing arguments to the theme function works.
747     $this->assertEquals($this->renderer->renderRoot($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
748   }
749
750   /**
751    * @covers ::render
752    * @covers ::doRender
753    * @covers \Drupal\Core\Render\RenderCache::get
754    * @covers \Drupal\Core\Render\RenderCache::set
755    * @covers \Drupal\Core\Render\RenderCache::createCacheID
756    */
757   public function testRenderCache() {
758     $this->setUpRequest();
759     $this->setupMemoryCache();
760
761     // Create an empty element.
762     $test_element = [
763       '#cache' => [
764         'keys' => ['render_cache_test'],
765         'tags' => ['render_cache_tag'],
766       ],
767       '#markup' => '',
768       'child' => [
769         '#cache' => [
770           'keys' => ['render_cache_test_child'],
771           'tags' => ['render_cache_tag_child:1', 'render_cache_tag_child:2'],
772         ],
773         '#markup' => '',
774       ],
775     ];
776
777     // Render the element and confirm that it goes through the rendering
778     // process (which will set $element['#printed']).
779     $element = $test_element;
780     $this->renderer->renderRoot($element);
781     $this->assertTrue(isset($element['#printed']), 'No cache hit');
782
783     // Render the element again and confirm that it is retrieved from the cache
784     // instead (so $element['#printed'] will not be set).
785     $element = $test_element;
786     $this->renderer->renderRoot($element);
787     $this->assertFalse(isset($element['#printed']), 'Cache hit');
788
789     // Test that cache tags are correctly collected from the render element,
790     // including the ones from its subchild.
791     $expected_tags = [
792       'render_cache_tag',
793       'render_cache_tag_child:1',
794       'render_cache_tag_child:2',
795     ];
796     $this->assertEquals($expected_tags, $element['#cache']['tags'], 'Cache tags were collected from the element and its subchild.');
797
798     // The cache item also has a 'rendered' cache tag.
799     $cache_item = $this->cacheFactory->get('render')->get('render_cache_test:en:stark');
800     $this->assertSame(Cache::mergeTags($expected_tags, ['rendered']), $cache_item->tags);
801   }
802
803   /**
804    * @covers ::render
805    * @covers ::doRender
806    * @covers \Drupal\Core\Render\RenderCache::get
807    * @covers \Drupal\Core\Render\RenderCache::set
808    * @covers \Drupal\Core\Render\RenderCache::createCacheID
809    *
810    * @dataProvider providerTestRenderCacheMaxAge
811    */
812   public function testRenderCacheMaxAge($max_age, $is_render_cached, $render_cache_item_expire) {
813     $this->setUpRequest();
814     $this->setupMemoryCache();
815
816     $element = [
817       '#cache' => [
818         'keys' => ['render_cache_test'],
819         'max-age' => $max_age,
820       ],
821       '#markup' => '',
822     ];
823     $this->renderer->renderRoot($element);
824
825     $cache_item = $this->cacheFactory->get('render')->get('render_cache_test:en:stark');
826     if (!$is_render_cached) {
827       $this->assertFalse($cache_item);
828     }
829     else {
830       $this->assertNotFalse($cache_item);
831       $this->assertSame($render_cache_item_expire, $cache_item->expire);
832     }
833   }
834
835   public function providerTestRenderCacheMaxAge() {
836     return [
837       [0, FALSE, NULL],
838       [60, TRUE, (int) $_SERVER['REQUEST_TIME'] + 60],
839       [Cache::PERMANENT, TRUE, -1],
840     ];
841   }
842
843   /**
844    * Tests that #cache_properties are properly handled.
845    *
846    * @param array $expected_results
847    *   An associative array of expected results keyed by property name.
848    *
849    * @covers ::render
850    * @covers ::doRender
851    * @covers \Drupal\Core\Render\RenderCache::get
852    * @covers \Drupal\Core\Render\RenderCache::set
853    * @covers \Drupal\Core\Render\RenderCache::createCacheID
854    * @covers \Drupal\Core\Render\RenderCache::getCacheableRenderArray
855    *
856    * @dataProvider providerTestRenderCacheProperties
857    */
858   public function testRenderCacheProperties(array $expected_results) {
859     $this->setUpRequest();
860     $this->setupMemoryCache();
861
862     $element = $original = [
863       '#cache' => [
864         'keys' => ['render_cache_test'],
865       ],
866       // Collect expected property names.
867       '#cache_properties' => array_keys(array_filter($expected_results)),
868       'child1' => ['#markup' => Markup::create('1')],
869       'child2' => ['#markup' => Markup::create('2')],
870       // Mark the value as safe.
871       '#custom_property' => Markup::create('custom_value'),
872       '#custom_property_array' => ['custom value'],
873     ];
874
875     $this->renderer->renderRoot($element);
876
877     $cache = $this->cacheFactory->get('render');
878     $data = $cache->get('render_cache_test:en:stark')->data;
879
880     // Check that parent markup is ignored when caching children's markup.
881     $this->assertEquals($data['#markup'] === '', (bool) Element::children($data));
882
883     // Check that the element properties are cached as specified.
884     foreach ($expected_results as $property => $expected) {
885       $cached = !empty($data[$property]);
886       $this->assertEquals($cached, (bool) $expected);
887       // Check that only the #markup key is preserved for children.
888       if ($cached) {
889         $this->assertEquals($data[$property], $original[$property]);
890       }
891     }
892     // #custom_property_array can not be a safe_cache_property.
893     $safe_cache_properties = array_diff(Element::properties(array_filter($expected_results)), ['#custom_property_array']);
894     foreach ($safe_cache_properties as $cache_property) {
895       $this->assertInstanceOf(MarkupInterface::class, $data[$cache_property], "$cache_property is marked as a safe string");
896     }
897   }
898
899   /**
900    * Data provider for ::testRenderCacheProperties().
901    *
902    * @return array
903    *   An array of associative arrays of expected results keyed by property
904    *   name.
905    */
906   public function providerTestRenderCacheProperties() {
907     return [
908       [[]],
909       [['child1' => 0, 'child2' => 0, '#custom_property' => 0, '#custom_property_array' => 0]],
910       [['child1' => 0, 'child2' => 0, '#custom_property' => 1, '#custom_property_array' => 0]],
911       [['child1' => 0, 'child2' => 1, '#custom_property' => 0, '#custom_property_array' => 0]],
912       [['child1' => 0, 'child2' => 1, '#custom_property' => 1, '#custom_property_array' => 0]],
913       [['child1' => 1, 'child2' => 0, '#custom_property' => 0, '#custom_property_array' => 0]],
914       [['child1' => 1, 'child2' => 0, '#custom_property' => 1, '#custom_property_array' => 0]],
915       [['child1' => 1, 'child2' => 1, '#custom_property' => 0, '#custom_property_array' => 0]],
916       [['child1' => 1, 'child2' => 1, '#custom_property' => 1, '#custom_property_array' => 0]],
917       [['child1' => 1, 'child2' => 1, '#custom_property' => 1, '#custom_property_array' => 1]],
918     ];
919   }
920
921   /**
922    * @covers ::addCacheableDependency
923    *
924    * @dataProvider providerTestAddCacheableDependency
925    */
926   public function testAddCacheableDependency(array $build, $object, array $expected) {
927     $this->renderer->addCacheableDependency($build, $object);
928     $this->assertEquals($build, $expected);
929   }
930
931   public function providerTestAddCacheableDependency() {
932     return [
933       // Empty render array, typical default cacheability.
934       [
935         [],
936         new TestCacheableDependency([], [], Cache::PERMANENT),
937         [
938           '#cache' => [
939             'contexts' => [],
940             'tags' => [],
941             'max-age' => Cache::PERMANENT,
942           ],
943         ],
944       ],
945       // Empty render array, some cacheability.
946       [
947         [],
948         new TestCacheableDependency(['user.roles'], ['foo'], Cache::PERMANENT),
949         [
950           '#cache' => [
951             'contexts' => ['user.roles'],
952             'tags' => ['foo'],
953             'max-age' => Cache::PERMANENT,
954           ],
955         ],
956       ],
957       // Cacheable render array, some cacheability.
958       [
959         [
960           '#cache' => [
961             'contexts' => ['theme'],
962             'tags' => ['bar'],
963             'max-age' => 600,
964           ]
965         ],
966         new TestCacheableDependency(['user.roles'], ['foo'], Cache::PERMANENT),
967         [
968           '#cache' => [
969             'contexts' => ['theme', 'user.roles'],
970             'tags' => ['bar', 'foo'],
971             'max-age' => 600,
972           ],
973         ],
974       ],
975       // Cacheable render array, no cacheability.
976       [
977         [
978           '#cache' => [
979             'contexts' => ['theme'],
980             'tags' => ['bar'],
981             'max-age' => 600,
982           ]
983         ],
984         new \stdClass(),
985         [
986           '#cache' => [
987             'contexts' => ['theme'],
988             'tags' => ['bar'],
989             'max-age' => 0,
990           ],
991         ],
992       ],
993     ];
994   }
995
996 }
997
998 class TestAccessClass {
999
1000   public static function accessTrue() {
1001     return TRUE;
1002   }
1003
1004   public static function accessFalse() {
1005     return FALSE;
1006   }
1007
1008   public static function accessResultAllowed() {
1009     return AccessResult::allowed();
1010   }
1011
1012   public static function accessResultForbidden() {
1013     return AccessResult::forbidden();
1014   }
1015
1016 }
1017
1018 class TestCallables {
1019
1020   public function preRenderPrinted($elements) {
1021     $elements['#printed'] = TRUE;
1022     return $elements;
1023   }
1024
1025 }