RendererPlaceholdersTest.php 43.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\Tests\Core\Render\RendererPlaceholdersTest.
 */

namespace Drupal\Tests\Core\Render;

10
use Drupal\Component\Utility\Crypt;
11 12
use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\Cache;
13
use Drupal\Core\Render\Markup;
14
use Drupal\Core\Security\TrustedCallbackInterface;
15
use Drupal\Core\Render\RenderContext;
16 17 18

/**
 * @coversDefaultClass \Drupal\Core\Render\Renderer
19 20
 * @covers \Drupal\Core\Render\RenderCache
 * @covers \Drupal\Core\Render\PlaceholderingRenderCache
21 22 23 24 25 26 27
 * @group Render
 */
class RendererPlaceholdersTest extends RendererTestBase {

  /**
   * {@inheritdoc}
   */
28
  protected function setUp(): void {
29 30 31 32 33 34 35 36 37 38
    // Disable the required cache contexts, so that this test can test just the
    // placeholder replacement behavior.
    $this->rendererConfig['required_cache_contexts'] = [];

    parent::setUp();
  }

  /**
   * Provides the two classes of placeholders: cacheable and uncacheable.
   *
39
   * I.e. with or without #cache[keys].
40 41 42 43
   *
   * Also, different types:
   * - A) automatically generated placeholder
   *   - 1) manually triggered (#create_placeholder = TRUE)
44 45 46 47 48 49 50 51 52 53 54
   *   - 2) automatically triggered (based on max-age = 0 at the top level)
   *   - 3) automatically triggered (based on high cardinality cache contexts at
   *        the top level)
   *   - 4) automatically triggered (based on high-invalidation frequency cache
   *        tags at the top level)
   *   - 5) automatically triggered (based on max-age = 0 in its subtree, i.e.
   *        via bubbling)
   *   - 6) automatically triggered (based on high cardinality cache contexts in
   *        its subtree, i.e. via bubbling)
   *   - 7) automatically triggered (based on high-invalidation frequency cache
   *        tags in its subtree, i.e. via bubbling)
55 56
   * - B) manually generated placeholder
   *
57 58
   * So, in total 2*8 = 16 permutations. (On one axis: uncacheable vs.
   * uncacheable = 2; on the other axis: A1–7 and B = 8.)
59
   *
60 61 62
   * @todo Case A5 is not yet supported by core. So that makes for only 14
   *   permutations currently, instead of 16. That will be done in
   *   https://www.drupal.org/node/2559847
63 64 65 66 67 68
   *
   * @return array
   */
  public function providerPlaceholders() {
    $args = [$this->randomContextValue()];

69
    $generate_placeholder_markup = function ($cache_keys = NULL) use ($args) {
70 71 72 73 74 75
      $token_render_array = [
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
      ];
      if (is_array($cache_keys)) {
        $token_render_array['#cache']['keys'] = $cache_keys;
      }
76
      $token = Crypt::hashBase64(serialize($token_render_array));
77
      // \Drupal\Core\Render\Markup::create() is necessary as the render
78 79
      // system would mangle this markup. As this is exactly what happens at
      // runtime this is a valid use-case.
80
      return Markup::create('<drupal-render-placeholder callback="Drupal\Tests\Core\Render\PlaceholdersTest::callback" arguments="' . '0=' . $args[0] . '" token="' . $token . '"></drupal-render-placeholder>');
81 82
    };

83 84 85 86 87
    $extract_placeholder_render_array = function ($placeholder_render_array) {
      return array_intersect_key($placeholder_render_array, ['#lazy_builder' => TRUE, '#cache' => TRUE]);
    };

    // Note the presence of '#create_placeholder'.
88 89 90 91 92 93 94 95 96 97 98 99 100 101
    $base_element_a1 = [
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
      ],
      'placeholder' => [
        '#cache' => [
          'contexts' => [],
        ],
        '#create_placeholder' => TRUE,
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
      ],
    ];
102 103
    // Note the absence of '#create_placeholder', presence of max-age=0 at the
    // top level.
104
    $base_element_a2 = [
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
      ],
      'placeholder' => [
        '#cache' => [
          'contexts' => [],
          'max-age' => 0,
        ],
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
      ],
    ];
    // Note the absence of '#create_placeholder', presence of high cardinality
    // cache context at the top level.
    $base_element_a3 = [
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
      ],
      'placeholder' => [
        '#cache' => [
          'contexts' => ['user'],
        ],
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
      ],
    ];
    // Note the absence of '#create_placeholder', presence of high-invalidation
    // frequency cache tag at the top level.
    $base_element_a4 = [
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
      ],
      'placeholder' => [
        '#cache' => [
          'contexts' => [],
          'tags' => ['current-temperature'],
        ],
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
      ],
148
    ];
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    // Note the absence of '#create_placeholder', presence of max-age=0 created
    // by the #lazy_builder callback.
    // @todo in https://www.drupal.org/node/2559847
    $base_element_a5 = [];
    // Note the absence of '#create_placeholder', presence of high cardinality
    // cache context created by the #lazy_builder callback.
    // @see \Drupal\Tests\Core\Render\PlaceholdersTest::callbackPerUser()
    $base_element_a6 = [
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
      ],
      'placeholder' => [
        '#cache' => [
          'contexts' => [],
        ],
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callbackPerUser', $args],
      ],
    ];
    // Note the absence of '#create_placeholder', presence of high-invalidation
    // frequency cache tag created by the #lazy_builder callback.
    // @see \Drupal\Tests\Core\Render\PlaceholdersTest::callbackTagCurrentTemperature()
    $base_element_a7 = [
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
      ],
      'placeholder' => [
        '#cache' => [
          'contexts' => [],
        ],
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callbackTagCurrentTemperature', $args],
      ],
    ];
185 186
    // Note the absence of '#create_placeholder', but the presence of
    // '#attached[placeholders]'.
187 188 189 190 191 192 193
    $base_element_b = [
      '#markup' => $generate_placeholder_markup(),
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
        'placeholders' => [
194
          (string) $generate_placeholder_markup() => [
195 196 197 198 199 200 201 202 203 204 205 206 207 208
            '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
          ],
        ],
      ],
    ];

    $keys = ['placeholder', 'output', 'can', 'be', 'render', 'cached', 'too'];

    $cases = [];

    // Case one: render array that has a placeholder that is:
    // - automatically created, but manually triggered (#create_placeholder = TRUE)
    // - uncacheable
    $element_without_cache_keys = $base_element_a1;
209
    $expected_placeholder_render_array = $extract_placeholder_render_array($base_element_a1['placeholder']);
210 211 212
    $cases[] = [
      $element_without_cache_keys,
      $args,
213
      $expected_placeholder_render_array,
214 215
      FALSE,
      [],
216 217
      [],
      [],
218 219 220 221 222 223 224
    ];

    // Case two: render array that has a placeholder that is:
    // - automatically created, but manually triggered (#create_placeholder = TRUE)
    // - cacheable
    $element_with_cache_keys = $base_element_a1;
    $element_with_cache_keys['placeholder']['#cache']['keys'] = $keys;
225
    $expected_placeholder_render_array['#cache']['keys'] = $keys;
226 227 228
    $cases[] = [
      $element_with_cache_keys,
      $args,
229
      $expected_placeholder_render_array,
230
      $keys,
231 232
      [],
      [],
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
      [
        '#markup' => '<p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => [],
          'tags' => [],
          'max-age' => Cache::PERMANENT,
        ],
      ],
    ];

    // Case three: render array that has a placeholder that is:
249 250 251 252 253 254 255 256 257 258
    // - automatically created, and automatically triggered due to max-age=0
    // - uncacheable
    $element_without_cache_keys = $base_element_a2;
    $expected_placeholder_render_array = $extract_placeholder_render_array($base_element_a2['placeholder']);
    $cases[] = [
      $element_without_cache_keys,
      $args,
      $expected_placeholder_render_array,
      FALSE,
      [],
259 260
      [],
      [],
261 262 263 264 265 266 267 268 269 270 271 272 273
    ];

    // Case four: render array that has a placeholder that is:
    // - automatically created, but automatically triggered due to max-age=0
    // - cacheable
    $element_with_cache_keys = $base_element_a2;
    $element_with_cache_keys['placeholder']['#cache']['keys'] = $keys;
    $expected_placeholder_render_array['#cache']['keys'] = $keys;
    $cases[] = [
      $element_with_cache_keys,
      $args,
      $expected_placeholder_render_array,
      FALSE,
274 275 276
      [],
      [],
      [],
277 278 279 280 281 282 283 284 285 286 287 288 289 290
    ];

    // Case five: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   cardinality cache contexts
    // - uncacheable
    $element_without_cache_keys = $base_element_a3;
    $expected_placeholder_render_array = $extract_placeholder_render_array($base_element_a3['placeholder']);
    $cases[] = [
      $element_without_cache_keys,
      $args,
      $expected_placeholder_render_array,
      FALSE,
      [],
291 292
      [],
      [],
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    ];

    // Case six: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   cardinality cache contexts
    // - cacheable
    $element_with_cache_keys = $base_element_a3;
    $element_with_cache_keys['placeholder']['#cache']['keys'] = $keys;
    $expected_placeholder_render_array['#cache']['keys'] = $keys;
    // The CID parts here consist of the cache keys plus the 'user' cache
    // context, which in this unit test is simply the given cache context token,
    // see \Drupal\Tests\Core\Render\RendererTestBase::setUp().
    $cid_parts = array_merge($keys, ['user']);
    $cases[] = [
      $element_with_cache_keys,
      $args,
      $expected_placeholder_render_array,
      $cid_parts,
311 312
      [],
      [],
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
      [
        '#markup' => '<p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => ['user'],
          'tags' => [],
          'max-age' => Cache::PERMANENT,
        ],
      ],
    ];

    // Case seven: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   invalidation frequency cache tags
    // - uncacheable
    $element_without_cache_keys = $base_element_a4;
    $expected_placeholder_render_array = $extract_placeholder_render_array($base_element_a4['placeholder']);
    $cases[] = [
      $element_without_cache_keys,
      $args,
      $expected_placeholder_render_array,
      FALSE,
      [],
340 341
      [],
      [],
342 343 344 345 346 347 348 349 350 351 352 353 354 355
    ];

    // Case eight: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   invalidation frequency cache tags
    // - cacheable
    $element_with_cache_keys = $base_element_a4;
    $element_with_cache_keys['placeholder']['#cache']['keys'] = $keys;
    $expected_placeholder_render_array['#cache']['keys'] = $keys;
    $cases[] = [
      $element_with_cache_keys,
      $args,
      $expected_placeholder_render_array,
      $keys,
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
      [],
      [],
      [
        '#markup' => '<p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => [],
          'tags' => ['current-temperature'],
          'max-age' => Cache::PERMANENT,
        ],
      ],
    ];

    // Case nine: render array that DOES NOT have a placeholder that is:
    // - NOT created, despite max-age=0 that is bubbled
    // - uncacheable
    // (because the render element with #lazy_builder does not have #cache[keys]
    // and hence the max-age=0 bubbles up further)
    // @todo in https://www.drupal.org/node/2559847

    // Case ten: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to max-age=0
    //   that is bubbled
    // - cacheable
    // @todo in https://www.drupal.org/node/2559847

    // Case eleven: render array that DOES NOT have a placeholder that is:
    // - NOT created, despite high cardinality cache contexts that are bubbled
    // - uncacheable
    $element_without_cache_keys = $base_element_a6;
    $expected_placeholder_render_array = $extract_placeholder_render_array($base_element_a6['placeholder']);
    $cases[] = [
      $element_without_cache_keys,
      $args,
      $expected_placeholder_render_array,
      FALSE,
      ['user'],
      [],
      [],
    ];

    // Case twelve: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   cardinality cache contexts that are bubbled
    // - cacheable
    $element_with_cache_keys = $base_element_a6;
    $element_with_cache_keys['placeholder']['#cache']['keys'] = $keys;
    $expected_placeholder_render_array['#cache']['keys'] = $keys;
    $cases[] = [
      $element_with_cache_keys,
      $args,
      $expected_placeholder_render_array,
      $keys,
      ['user'],
      [],
      [
        '#markup' => '<p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => ['user'],
          'tags' => [],
          'max-age' => Cache::PERMANENT,
        ],
      ],
    ];

    // Case thirteen: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   invalidation frequency cache tags that are bubbled
    // - uncacheable
    $element_without_cache_keys = $base_element_a7;
    $expected_placeholder_render_array = $extract_placeholder_render_array($base_element_a7['placeholder']);
    $cases[] = [
      $element_without_cache_keys,
      $args,
      $expected_placeholder_render_array,
      FALSE,
      [],
      ['current-temperature'],
      [],
    ];

    // Case fourteen: render array that has a placeholder that is:
    // - automatically created, and automatically triggered due to high
    //   invalidation frequency cache tags that are bubbled
    // - cacheable
    $element_with_cache_keys = $base_element_a7;
    $element_with_cache_keys['placeholder']['#cache']['keys'] = $keys;
    $expected_placeholder_render_array['#cache']['keys'] = $keys;
    $cases[] = [
      $element_with_cache_keys,
      $args,
      $expected_placeholder_render_array,
      $keys,
      [],
      [],
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
      [
        '#markup' => '<p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => [],
          'tags' => ['current-temperature'],
          'max-age' => Cache::PERMANENT,
        ],
      ],
    ];

475
    // Case fifteen: render array that has a placeholder that is:
476 477 478
    // - manually created
    // - uncacheable
    $x = $base_element_b;
479 480
    $expected_placeholder_render_array = $x['#attached']['placeholders'][(string) $generate_placeholder_markup()];
    unset($x['#attached']['placeholders'][(string) $generate_placeholder_markup()]['#cache']);
481 482 483
    $cases[] = [
      $x,
      $args,
484
      $expected_placeholder_render_array,
485 486
      FALSE,
      [],
487 488
      [],
      [],
489 490
    ];

491
    // Case sixteen: render array that has a placeholder that is:
492 493 494
    // - manually created
    // - cacheable
    $x = $base_element_b;
495
    $x['#markup'] = $placeholder_markup = $generate_placeholder_markup($keys);
496
    $placeholder_markup = (string) $placeholder_markup;
497
    $x['#attached']['placeholders'] = [
498
      $placeholder_markup => [
499 500 501 502
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
        '#cache' => ['keys' => $keys],
      ],
    ];
503
    $expected_placeholder_render_array = $x['#attached']['placeholders'][$placeholder_markup];
504 505 506
    $cases[] = [
      $x,
      $args,
507
      $expected_placeholder_render_array,
508
      $keys,
509 510
      [],
      [],
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
      [
        '#markup' => '<p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => [],
          'tags' => [],
          'max-age' => Cache::PERMANENT,
        ],
      ],
    ];

    return $cases;
  }

  /**
   * Generates an element with a placeholder.
   *
   * @return array
   *   An array containing:
   *   - A render array containing a placeholder.
   *   - The context used for that #lazy_builder callback.
   */
  protected function generatePlaceholderElement() {
    $args = [$this->randomContextValue()];
    $test_element = [];
    $test_element['#attached']['drupalSettings']['foo'] = 'bar';
    $test_element['placeholder']['#cache']['keys'] = ['placeholder', 'output', 'can', 'be', 'render', 'cached', 'too'];
    $test_element['placeholder']['#cache']['contexts'] = [];
    $test_element['placeholder']['#create_placeholder'] = TRUE;
    $test_element['placeholder']['#lazy_builder'] = ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args];

    return [$test_element, $args];
  }

  /**
alexpott's avatar
alexpott committed
550
   * @param false|array $cid_parts
551 552 553
   * @param string[] $bubbled_cache_contexts
   *   Additional cache contexts that were bubbled when the placeholder was
   *   rendered.
554 555
   * @param array $expected_data
   *   A render array with the expected values.
556
   */
557
  protected function assertPlaceholderRenderCache($cid_parts, array $bubbled_cache_contexts, array $expected_data) {
558
    if ($cid_parts !== FALSE) {
559 560 561 562 563 564 565 566 567 568 569 570 571
      if ($bubbled_cache_contexts) {
        // Verify render cached placeholder.
        $cached_element = $this->memoryCache->get(implode(':', $cid_parts))->data;
        $expected_redirect_element = [
          '#cache_redirect' => TRUE,
          '#cache' => $expected_data['#cache'] + [
            'keys' => $cid_parts,
            'bin' => 'render',
          ],
        ];
        $this->assertEquals($expected_redirect_element, $cached_element, 'The correct cache redirect exists.');
      }

572
      // Verify render cached placeholder.
573 574
      $cached = $this->memoryCache->get(implode(':', array_merge($cid_parts, $bubbled_cache_contexts)));
      $cached_element = $cached->data;
575
      $this->assertEquals($expected_data, $cached_element, 'The correct data is cached: the stored #markup and #attached properties are not affected by the placeholder being replaced.');
576 577
    }
  }
578

579 580 581 582 583 584
  /**
   * @covers ::render
   * @covers ::doRender
   *
   * @dataProvider providerPlaceholders
   */
585
  public function testUncacheableParent($element, $args, array $expected_placeholder_render_array, $placeholder_cid_parts, array $bubbled_cache_contexts, array $bubbled_cache_tags, array $placeholder_expected_render_cache_array) {
586
    if ($placeholder_cid_parts) {
587 588 589 590 591 592 593 594 595 596 597
      $this->setupMemoryCache();
    }
    else {
      $this->setUpUnusedCache();
    }

    $this->setUpRequest('GET');

    // No #cache on parent element.
    $element['#prefix'] = '<p>#cache disabled</p>';
    $output = $this->renderer->renderRoot($element);
598 599
    $this->assertSame('<p>#cache disabled</p><p>This is a rendered placeholder!</p>', (string) $output, 'Output is overridden.');
    $this->assertSame('<p>#cache disabled</p><p>This is a rendered placeholder!</p>', (string) $element['#markup'], '#markup is overridden.');
600 601 602 603 604
    $expected_js_settings = [
      'foo' => 'bar',
      'dynamic_animal' => $args[0],
    ];
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the one added by the placeholder #lazy_builder callback exist.');
605
    $this->assertPlaceholderRenderCache($placeholder_cid_parts, $bubbled_cache_contexts, $placeholder_expected_render_cache_array);
606 607 608 609 610 611 612 613 614 615 616
  }

  /**
   * @covers ::render
   * @covers ::doRender
   * @covers \Drupal\Core\Render\RenderCache::get
   * @covers \Drupal\Core\Render\RenderCache::set
   * @covers \Drupal\Core\Render\RenderCache::createCacheID
   *
   * @dataProvider providerPlaceholders
   */
617
  public function testCacheableParent($test_element, $args, array $expected_placeholder_render_array, $placeholder_cid_parts, array $bubbled_cache_contexts, array $bubbled_cache_tags, array $placeholder_expected_render_cache_array) {
618 619 620 621 622
    $element = $test_element;
    $this->setupMemoryCache();

    $this->setUpRequest('GET');

623
    $token = Crypt::hashBase64(serialize($expected_placeholder_render_array));
624 625
    $placeholder_callback = $expected_placeholder_render_array['#lazy_builder'][0];
    $expected_placeholder_markup = '<drupal-render-placeholder callback="' . $placeholder_callback . '" arguments="0=' . $args[0] . '" token="' . $token . '"></drupal-render-placeholder>';
626 627 628 629 630 631
    $this->assertSame($expected_placeholder_markup, Html::normalize($expected_placeholder_markup), 'Placeholder unaltered by Html::normalize() which is used by FilterHtmlCorrector.');

    // GET request: #cache enabled, cache miss.
    $element['#cache'] = ['keys' => ['placeholder_test_GET']];
    $element['#prefix'] = '<p>#cache enabled, GET</p>';
    $output = $this->renderer->renderRoot($element);
632
    $this->assertSame('<p>#cache enabled, GET</p><p>This is a rendered placeholder!</p>', (string) $output, 'Output is overridden.');
633
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
634
    $this->assertSame('<p>#cache enabled, GET</p><p>This is a rendered placeholder!</p>', (string) $element['#markup'], '#markup is overridden.');
635 636 637 638 639
    $expected_js_settings = [
      'foo' => 'bar',
      'dynamic_animal' => $args[0],
    ];
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the one added by the placeholder #lazy_builder callback exist.');
640
    $this->assertPlaceholderRenderCache($placeholder_cid_parts, $bubbled_cache_contexts, $placeholder_expected_render_cache_array);
641 642

    // GET request: validate cached data.
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    $cached = $this->memoryCache->get('placeholder_test_GET');
    // There are three edge cases, where the shape of the render cache item for
    // the parent (with CID 'placeholder_test_GET') is vastly different. These
    // are the cases where:
    // - the placeholder is uncacheable (because it has no #cache[keys]), and;
    // - cacheability metadata that meets auto_placeholder_conditions is bubbled
    $has_uncacheable_lazy_builder = !isset($test_element['placeholder']['#cache']['keys']) && isset($test_element['placeholder']['#lazy_builder']);
    // Edge cases: always where both bubbling of an auto-placeholdering
    // condition happens from within a #lazy_builder that is uncacheable.
    // - uncacheable + A5 (cache max-age)
    // @todo in https://www.drupal.org/node/2559847
    // - uncacheable + A6 (cache context)
    $edge_case_a6_uncacheable = $has_uncacheable_lazy_builder && $test_element['placeholder']['#lazy_builder'][0] === 'Drupal\Tests\Core\Render\PlaceholdersTest::callbackPerUser';
    // - uncacheable + A7 (cache tag)
    $edge_case_a7_uncacheable = $has_uncacheable_lazy_builder && $test_element['placeholder']['#lazy_builder'][0] === 'Drupal\Tests\Core\Render\PlaceholdersTest::callbackTagCurrentTemperature';
    // The redirect-cacheable edge case: a high-cardinality cache context is
    // bubbled from a #lazy_builder callback for an uncacheable placeholder. The
    // element containing the uncacheable placeholder has cache keys set, and
    // due to the bubbled cache contexts it creates a cache redirect.
    if ($edge_case_a6_uncacheable) {
      $cached_element = $cached->data;
      $expected_redirect = [
        '#cache_redirect' => TRUE,
        '#cache' => [
          'keys' => ['placeholder_test_GET'],
          'contexts' => ['user'],
          'tags' => [],
          'max-age' => Cache::PERMANENT,
          'bin' => 'render',
672
        ],
673 674 675 676 677 678 679 680 681 682
      ];
      $this->assertEquals($expected_redirect, $cached_element);
      // Follow the redirect.
      $cached_element = $this->memoryCache->get('placeholder_test_GET:' . implode(':', $bubbled_cache_contexts))->data;
      $expected_element = [
        '#markup' => '<p>#cache enabled, GET</p><p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'foo' => 'bar',
            'dynamic_animal' => $args[0],
683 684
          ],
        ],
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
        '#cache' => [
          'contexts' => $bubbled_cache_contexts,
          'tags' => [],
          'max-age' => Cache::PERMANENT,
        ],
      ];
      $this->assertEquals($expected_element, $cached_element, 'The parent is render cached with a redirect in ase a cache context is bubbled from an uncacheable child (no #cache[keys]) with a #lazy_builder.');
    }
    // The normally cacheable edge case: a high-invalidation frequency cache tag
    // is bubbled from a #lazy_builder callback for an uncacheable placeholder.
    // The element containing the uncacheable placeholder has cache keys set,
    // and also has the bubbled cache tags.
    elseif ($edge_case_a7_uncacheable) {
      $cached_element = $cached->data;
      $expected_element = [
        '#markup' => '<p>#cache enabled, GET</p><p>This is a rendered placeholder!</p>',
        '#attached' => [
          'drupalSettings' => [
            'foo' => 'bar',
            'dynamic_animal' => $args[0],
          ],
        ],
        '#cache' => [
          'contexts' => [],
          'tags' => $bubbled_cache_tags,
          'max-age' => Cache::PERMANENT,
        ],
      ];
      $this->assertEquals($expected_element, $cached_element, 'The correct data is cached: the stored #markup and #attached properties are not affected by placeholder #lazy_builder callbacks.');
    }
    // The regular case.
    else {
      $cached_element = $cached->data;
      $expected_element = [
        '#markup' => '<p>#cache enabled, GET</p>' . $expected_placeholder_markup,
        '#attached' => [
          'drupalSettings' => [
            'foo' => 'bar',
          ],
          'placeholders' => [
            $expected_placeholder_markup => [
              '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', $args],
            ],
          ],
        ],
        '#cache' => [
          'contexts' => [],
          'tags' => $bubbled_cache_tags,
          'max-age' => Cache::PERMANENT,
        ],
      ];
      $expected_element['#attached']['placeholders'][$expected_placeholder_markup] = $expected_placeholder_render_array;
      $this->assertEquals($expected_element, $cached_element, 'The correct data is cached: the stored #markup and #attached properties are not affected by placeholder #lazy_builder callbacks.');
    }
739 740 741 742 743 744

    // GET request: #cache enabled, cache hit.
    $element = $test_element;
    $element['#cache'] = ['keys' => ['placeholder_test_GET']];
    $element['#prefix'] = '<p>#cache enabled, GET</p>';
    $output = $this->renderer->renderRoot($element);
745
    $this->assertSame('<p>#cache enabled, GET</p><p>This is a rendered placeholder!</p>', (string) $output, 'Output is overridden.');
746
    $this->assertFalse(isset($element['#printed']), 'Cache hit');
747
    $this->assertSame('<p>#cache enabled, GET</p><p>This is a rendered placeholder!</p>', (string) $element['#markup'], '#markup is overridden.');
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    $expected_js_settings = [
      'foo' => 'bar',
      'dynamic_animal' => $args[0],
    ];
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the one added by the placeholder #lazy_builder callback exist.');
  }

  /**
   * @covers ::render
   * @covers ::doRender
   * @covers \Drupal\Core\Render\RenderCache::get
   * @covers ::replacePlaceholders
   *
   * @dataProvider providerPlaceholders
   */
  public function testCacheableParentWithPostRequest($test_element, $args) {
    $this->setUpUnusedCache();

    // Verify behavior when handling a non-GET request, e.g. a POST request:
    // also in that case, placeholders must be replaced.
    $this->setUpRequest('POST');

    // POST request: #cache enabled, cache miss.
    $element = $test_element;
    $element['#cache'] = ['keys' => ['placeholder_test_POST']];
    $element['#prefix'] = '<p>#cache enabled, POST</p>';
    $output = $this->renderer->renderRoot($element);
775
    $this->assertSame('<p>#cache enabled, POST</p><p>This is a rendered placeholder!</p>', (string) $output, 'Output is overridden.');
776
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
777
    $this->assertSame('<p>#cache enabled, POST</p><p>This is a rendered placeholder!</p>', (string) $element['#markup'], '#markup is overridden.');
778 779 780 781 782 783 784 785
    $expected_js_settings = [
      'foo' => 'bar',
      'dynamic_animal' => $args[0],
    ];
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the one added by the placeholder #lazy_builder callback exist.');

    // Even when the child element's placeholder is cacheable, it should not
    // generate a render cache item.
786
    $this->assertPlaceholderRenderCache(FALSE, [], []);
787 788
  }

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
  /**
   * @covers ::render
   * @covers ::doRender
   * @covers \Drupal\Core\Render\RenderCache::get
   * @covers \Drupal\Core\Render\PlaceholderingRenderCache::get
   * @covers \Drupal\Core\Render\PlaceholderingRenderCache::set
   * @covers ::replacePlaceholders
   *
   * @dataProvider providerPlaceholders
   */
  public function testPlaceholderingDisabledForPostRequests($test_element, $args) {
    $this->setUpUnusedCache();
    $this->setUpRequest('POST');

    $element = $test_element;

    // Render without replacing placeholders, to allow this test to see which
    // #attached[placeholders] there are, if any.
    $this->renderer->executeInRenderContext(new RenderContext(), function () use (&$element) {
      return $this->renderer->render($element);
    });
    // Only test cases where the placeholders have been specified manually are
    // allowed to have placeholders. This means that of the different situations
    // listed in providerPlaceholders(), only type B can have attached
    // placeholders. Everything else, whether:
    // 1. manual placeholdering
    // 2. automatic placeholdering via already-present cacheability metadata
    // 3. automatic placeholdering via bubbled cacheability metadata
    // All three of those should NOT result in placeholders.
    if (!isset($test_element['#attached']['placeholders'])) {
      $this->assertFalse(isset($element['#attached']['placeholders']), 'No placeholders created.');
    }
  }

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
  /**
   * Tests a placeholder that adds another placeholder.
   *
   * E.g. when rendering a node in a placeholder the rendering of that node
   * needs a placeholder of its own to be executed (to render the node links).
   *
   * @covers ::render
   * @covers ::doRender
   * @covers ::replacePlaceholders
   */
  public function testRecursivePlaceholder() {
    $args = [$this->randomContextValue()];
    $element = [];
    $element['#create_placeholder'] = TRUE;
    $element['#lazy_builder'] = ['Drupal\Tests\Core\Render\RecursivePlaceholdersTest::callback', $args];

    $output = $this->renderer->renderRoot($element);
    $this->assertEquals('<p>This is a rendered placeholder!</p>', $output, 'The output has been modified by the indirect, recursive placeholder #lazy_builder callback.');
841
    $this->assertSame((string) $element['#markup'], '<p>This is a rendered placeholder!</p>', '#markup is overridden by the indirect, recursive placeholder #lazy_builder callback.');
842 843 844 845 846 847 848 849 850 851 852 853 854 855
    $expected_js_settings = [
      'dynamic_animal' => $args[0],
    ];
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified by the indirect, recursive placeholder #lazy_builder callback.');
  }

  /**
   * @covers ::render
   * @covers ::doRender
   */
  public function testInvalidLazyBuilder() {
    $element = [];
    $element['#lazy_builder'] = '\Drupal\Tests\Core\Render\PlaceholdersTest::callback';

856 857
    $this->expectException(\DomainException::class);
    $this->expectExceptionMessage('The #lazy_builder property must have an array as a value.');
858 859 860 861 862 863 864 865 866 867 868
    $this->renderer->renderRoot($element);
  }

  /**
   * @covers ::render
   * @covers ::doRender
   */
  public function testInvalidLazyBuilderArguments() {
    $element = [];
    $element['#lazy_builder'] = ['\Drupal\Tests\Core\Render\PlaceholdersTest::callback', 'arg1', 'arg2'];

869 870
    $this->expectException(\DomainException::class);
    $this->expectExceptionMessage('The #lazy_builder property must have an array as a value, containing two values: the callback, and the arguments for the callback.');
871 872 873 874 875 876 877 878 879 880 881
    $this->renderer->renderRoot($element);
  }

  /**
   * @covers ::render
   * @covers ::doRender
   *
   * @see testNonScalarLazybuilderCallbackContext
   */
  public function testScalarLazybuilderCallbackContext() {
    $element = [];
882 883 884 885 886 887 888 889 890 891
    $element['#lazy_builder'] = [
      '\Drupal\Tests\Core\Render\PlaceholdersTest::callback',
      [
        'string' => 'foo',
        'bool' => TRUE,
        'int' => 1337,
        'float' => 3.14,
        'null' => NULL,
      ],
    ];
892

893
    $result = $this->renderer->renderRoot($element);
894
    $this->assertInstanceOf('\Drupal\Core\Render\Markup', $result);
895
    $this->assertEquals('<p>This is a rendered placeholder!</p>', (string) $result);
896 897 898 899 900 901 902 903
  }

  /**
   * @covers ::render
   * @covers ::doRender
   */
  public function testNonScalarLazybuilderCallbackContext() {
    $element = [];
904 905 906 907 908 909 910 911 912 913 914 915
    $element['#lazy_builder'] = [
      '\Drupal\Tests\Core\Render\PlaceholdersTest::callback',
      [
        'string' => 'foo',
        'bool' => TRUE,
        'int' => 1337,
        'float' => 3.14,
        'null' => NULL,
        // array is not one of the scalar types.
        'array' => ['hi!'],
      ],
    ];
916

917 918
    $this->expectException(\DomainException::class);
    $this->expectExceptionMessage("A #lazy_builder callback's context may only contain scalar values or NULL.");
919 920 921 922 923 924 925 926 927 928 929 930 931
    $this->renderer->renderRoot($element);
  }

  /**
   * @covers ::render
   * @covers ::doRender
   */
  public function testChildrenPlusBuilder() {
    $element = [];
    $element['#lazy_builder'] = ['Drupal\Tests\Core\Render\RecursivePlaceholdersTest::callback', []];
    $element['child_a']['#markup'] = 'Oh hai!';
    $element['child_b']['#markup'] = 'kthxbai';

932 933
    $this->expectException(\DomainException::class);
    $this->expectExceptionMessage('When a #lazy_builder callback is specified, no children can exist; all children must be generated by the #lazy_builder callback. You specified the following children: child_a, child_b.');
934 935 936 937 938 939 940 941 942 943 944 945 946
    $this->renderer->renderRoot($element);
  }

  /**
   * @covers ::render
   * @covers ::doRender
   */
  public function testPropertiesPlusBuilder() {
    $element = [];
    $element['#lazy_builder'] = ['Drupal\Tests\Core\Render\RecursivePlaceholdersTest::callback', []];
    $element['#llama'] = '#awesome';
    $element['#piglet'] = '#cute';

947 948
    $this->expectException(\DomainException::class);
    $this->expectExceptionMessage('When a #lazy_builder callback is specified, no properties can exist; all properties must be generated by the #lazy_builder callback. You specified the following properties: #llama, #piglet.');
949 950 951 952 953 954 955 956 957 958 959
    $this->renderer->renderRoot($element);
  }

  /**
   * @covers ::render
   * @covers ::doRender
   */
  public function testCreatePlaceholderPropertyWithoutLazyBuilder() {
    $element = [];
    $element['#create_placeholder'] = TRUE;

960 961
    $this->expectException(\LogicException::class);
    $this->expectExceptionMessage('When #create_placeholder is set, a #lazy_builder callback must be present as well.');
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    $this->renderer->renderRoot($element);
  }

  /**
   * Create an element with a child and subchild. Each element has the same
   * #lazy_builder callback, but with different contexts. They don't modify
   * markup, only attach additional drupalSettings.
   *
   * @covers ::render
   * @covers ::doRender
   * @covers \Drupal\Core\Render\RenderCache::get
   * @covers ::replacePlaceholders
   */
  public function testRenderChildrenPlaceholdersDifferentArguments() {
    $this->setUpRequest();
    $this->setupMemoryCache();
    $this->cacheContextsManager->expects($this->any())
      ->method('convertTokensToKeys')
      ->willReturnArgument(0);
    $this->controllerResolver->expects($this->any())
      ->method('getControllerFromDefinition')
      ->willReturnArgument(0);
    $this->setupThemeManagerForDetails();

    $args_1 = ['foo', TRUE];
    $args_2 = ['bar', TRUE];
    $args_3 = ['baz', TRUE];
    $test_element = $this->generatePlaceholdersWithChildrenTestElement($args_1, $args_2, $args_3);

    $element = $test_element;
    $output = $this->renderer->renderRoot($element);
    $expected_output = <<<HTML
<details>
  <summary>Parent</summary>
  <div class="details-wrapper"><details>
  <summary>Child</summary>
  <div class="details-wrapper">Subchild</div>
</details></div>
</details>
HTML;
1002
    $this->assertSame($expected_output, (string) $output, 'Output is not overridden.');
1003
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
1004
    $this->assertSame($expected_output, (string) $element['#markup'], '#markup is not overridden.');
1005 1006 1007 1008 1009 1010 1011
    $expected_js_settings = [
      'foo' => 'bar',
      'dynamic_animal' => [$args_1[0] => TRUE, $args_2[0] => TRUE, $args_3[0] => TRUE],
    ];
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the ones added by each placeholder #lazy_builder callback exist.');

    // GET request: validate cached data.
1012
    $cached_element = $this->memoryCache->get('simpletest:renderer:children_placeholders')->data;
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    $expected_element = [
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
        'placeholders' => [
          'parent-x-parent' => [
            '#lazy_builder' => [__NAMESPACE__ . '\\PlaceholdersTest::callback', $args_1],
          ],
          'child-x-child' => [
            '#lazy_builder' => [__NAMESPACE__ . '\\PlaceholdersTest::callback', $args_2],
          ],
          'subchild-x-subchild' => [
            '#lazy_builder' => [__NAMESPACE__ . '\\PlaceholdersTest::callback', $args_3],
          ],
        ],
      ],
      '#cache' => [
        'contexts' => [],
        'tags' => [],
        'max-age' => Cache::PERMANENT,
      ],
    ];

1037 1038
    // Verify that the correct data is cached: the stored #markup is not
    // affected by placeholder #lazy_builder callbacks.
1039 1040
    $dom = Html::load($cached_element['#markup']);
    $xpath = new \DOMXPath($dom);
1041 1042 1043
    $this->assertNotEmpty($xpath->query('//details/summary[text()="Parent"]')->length);
    $this->assertNotEmpty($xpath->query('//details/div[@class="details-wrapper"]/details/summary[text()="Child"]')->length);
    $this->assertNotEmpty($xpath->query('//details/div[@class="details-wrapper"]/details/div[@class="details-wrapper" and text()="Subchild"]')->length);
1044 1045 1046 1047 1048 1049 1050 1051

    // Remove markup because it's compared above in the xpath.
    unset($cached_element['#markup']);
    $this->assertEquals($cached_element, $expected_element, 'The correct data is cached: the stored #attached properties are not affected by placeholder #lazy_builder callbacks.');

    // GET request: #cache enabled, cache hit.
    $element = $test_element;
    $output = $this->renderer->renderRoot($element);
1052
    $this->assertSame($expected_output, (string) $output, 'Output is not overridden.');
1053 1054 1055 1056 1057 1058 1059 1060
    $this->assertFalse(isset($element['#printed']), 'Cache hit');
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the ones added by each placeholder #lazy_builder callback exist.');

    // Use the exact same element, but now unset #cache; ensure we get the same
    // result.
    unset($test_element['#cache']);
    $element = $test_element;
    $output = $this->renderer->renderRoot($element);
1061 1062
    $this->assertSame($expected_output, (string) $output, 'Output is not overridden.');
    $this->assertSame($expected_output, (string) $element['#markup'], '#markup is not overridden.');
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    $this->assertSame($element['#attached']['drupalSettings'], $expected_js_settings, '#attached is modified; both the original JavaScript setting and the ones added by each #lazy_builder callback exist.');
  }

  /**
   * Generates an element with placeholders at 3 levels.
   *
   * @param array $args_1
   *   The arguments for the placeholder at level 1.
   * @param array $args_2
   *   The arguments for the placeholder at level 2.
   * @param array $args_3
   *   The arguments for the placeholder at level 3.
   *
   * @return array
   *   The generated render array for testing.
   */
  protected function generatePlaceholdersWithChildrenTestElement(array $args_1, array $args_2, array $args_3) {
    $test_element = [
      '#type' => 'details',
      '#cache' => [
1083
        'keys' => ['simpletest', 'renderer', 'children_placeholders'],
1084 1085 1086 1087 1088 1089 1090 1091
      ],
      '#title' => 'Parent',
      '#attached' => [
        'drupalSettings' => [
          'foo' => 'bar',
        ],
        'placeholders' => [
          'parent-x-parent' => [
1092
            '#lazy_builder' => [__NAMESPACE__ . '\\PlaceholdersTest::callback', $args_1],
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
          ],
        ],
      ],
    ];
    $test_element['child'] = [
      '#type' => 'details',
      '#attached' => [
        'placeholders' => [
          'child-x-child' => [
            '#lazy_builder' => [__NAMESPACE__ . '\\PlaceholdersTest::callback', $args_2],
          ],
        ],
      ],
      '#title' => 'Child',
    ];
    $test_element['child']['subchild'] = [
      '#attached' => [
        'placeholders' => [
          'subchild-x-subchild' => [
            '#lazy_builder' => [__NAMESPACE__ . '\\PlaceholdersTest::callback', $args_3],
          ],
        ],
      ],
      '#markup' => 'Subchild',
    ];
    return $test_element;
  }

  /**
1122
   * @return \Drupal\Core\Theme\ThemeManagerInterface|\PHPUnit\Framework\MockObject\Builder\InvocationMocker
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
   */
  protected function setupThemeManagerForDetails() {
    return $this->themeManager->expects($this->any())
      ->method('render')
      ->willReturnCallback(function ($theme, array $vars) {
        $output = <<<'EOS'
<details>
  <summary>{{ title }}</summary>
  <div class="details-wrapper">{{ children }}</div>
</details>
EOS;
        $output = str_replace([
          '{{ title }}',
1136
          '{{ children }}',
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
        ], [$vars['#title'], $vars['#children']], $output);
        return $output;
      });
  }

}

/**
 * @see \Drupal\Tests\Core\Render\RendererPlaceholdersTest::testRecursivePlaceholder()
 */
1147
class RecursivePlaceholdersTest implements TrustedCallbackInterface {
1148 1149 1150 1151 1152

  /**
   * #lazy_builder callback; bubbles another placeholder.
   *
   * @param string $animal
1153
   *   An animal.
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
   *
   * @return array
   *   A renderable array.
   */
  public static function callback($animal) {
    return [
      'another' => [
        '#create_placeholder' => TRUE,
        '#lazy_builder' => ['Drupal\Tests\Core\Render\PlaceholdersTest::callback', [$animal]],
      ],
    ];
  }

1167 1168 1169 1170 1171 1172 1173
  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return ['callback'];
  }

1174
}