View source
<?php
namespace Drupal\Tests\twig_tweak\Kernel;
use Drupal\block\Entity\Block;
use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\Cache;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
final class RegionViewBuilderTest extends KernelTestBase {
use UserCreationTrait;
protected static $modules = [
'twig_tweak',
'twig_tweak_test',
'user',
'system',
'block',
];
public function setUp() : void {
parent::setUp();
$this
->installEntitySchema('block');
$this->container
->get('theme_installer')
->install([
'stable',
]);
$values = [
'id' => 'public_block',
'plugin' => 'system_powered_by_block',
'theme' => 'stable',
'region' => 'sidebar_first',
];
Block::create($values)
->save();
$values = [
'id' => 'private_block',
'plugin' => 'system_powered_by_block',
'theme' => 'stable',
'region' => 'sidebar_first',
];
Block::create($values)
->save();
}
public function testRegionViewBuilder() : void {
$view_builder = $this->container
->get('twig_tweak.region_view_builder');
$renderer = $this->container
->get('renderer');
$build = $view_builder
->build('sidebar_first');
$expected_build = [
'#cache' => [
'contexts' => [],
'tags' => [
'config:block_list',
],
'max-age' => Cache::PERMANENT,
],
];
self::assertSame($expected_build, $build);
$build = $view_builder
->build('sidebar_first', 'stable');
$expected_build = [
'public_block' => [
'#cache' => [
'keys' => [
'entity_view',
'block',
'public_block',
],
'contexts' => [],
'tags' => [
'block_view',
'config:block.block.public_block',
],
'max-age' => Cache::PERMANENT,
],
'#weight' => NULL,
'#lazy_builder' => [
'Drupal\\block\\BlockViewBuilder::lazyBuilder',
[
'public_block',
'full',
NULL,
],
],
],
'#region' => 'sidebar_first',
'#theme_wrappers' => [
'region',
],
'#cache' => [
'contexts' => [
'user',
],
'tags' => [
'config:block.block.public_block',
'config:block_list',
'tag_for_private_block',
'tag_for_public_block',
],
'max-age' => 123,
],
];
self::assertSame($expected_build, $build);
$expected_html = <<<'HTML'
<div>
<div id="block-public-block">
<span>Powered by <a href="https://www.drupal.org">Drupal</a></span>
</div>
</div>
HTML;
$actual_html = $renderer
->renderPlain($build);
self::assertSame(self::normalizeHtml($expected_html), self::normalizeHtml($actual_html));
$this->container
->get('config.factory')
->getEditable('system.theme')
->set('default', 'stable')
->save();
$build = $view_builder
->build('sidebar_first');
self::assertSame($expected_build, $build);
Html::resetSeenIds();
$actual_html = $renderer
->renderPlain($expected_build);
self::assertSame(self::normalizeHtml($expected_html), self::normalizeHtml($actual_html));
}
private static function normalizeHtml(string $html) : string {
return rtrim(preg_replace([
'#\\s{2,}#',
'#\\n#',
], '', $html));
}
}