View source
<?php
namespace Drupal\KernelTests\Core\Theme;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Component\Render\MarkupTrait;
use Drupal\Core\GeneratedLink;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\Markup;
use Drupal\Core\Site\Settings;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\KernelTests\KernelTestBase;
class TwigMarkupInterfaceTest extends KernelTestBase {
public static $modules = [
'language',
];
public function testMarkupInterfaceEmpty($expected, $variable) {
$this
->assertEquals($expected, $this
->renderObjectWithTwig($variable));
}
public function providerTestMarkupInterfaceEmpty() {
return [
'empty TranslatableMarkup' => [
'',
new TranslatableMarkup(''),
],
'non-empty TranslatableMarkup' => [
'<span>test</span>',
new TranslatableMarkup('test'),
],
'empty FormattableMarkup' => [
'',
new FormattableMarkup('', [
'@foo' => 'bar',
]),
],
'non-empty FormattableMarkup' => [
'<span>bar</span>',
new FormattableMarkup('@foo', [
'@foo' => 'bar',
]),
],
'non-empty Markup' => [
'<span>test</span>',
Markup::create('test'),
],
'empty GeneratedLink' => [
'',
new GeneratedLink(),
],
'non-empty GeneratedLink' => [
'<span><a hef="http://www.example.com">test</a></span>',
(new GeneratedLink())
->setGeneratedLink('<a hef="http://www.example.com">test</a>'),
],
'empty SafeMarkupTestMarkup' => [
'<span></span>',
SafeMarkupTestMarkup::create(''),
],
'non-empty SafeMarkupTestMarkup' => [
'<span>test</span>',
SafeMarkupTestMarkup::create('test'),
],
];
}
public function testEmptyTranslation() {
$settings = Settings::getAll();
$settings['locale_custom_strings_en'] = [
'' => [
'test' => '',
],
];
new Settings($settings);
$variable = new TranslatableMarkup('test');
$this
->assertEquals('', $this
->renderObjectWithTwig($variable));
$variable = new TranslatableMarkup('test', [], [
'langcode' => 'de',
]);
$this
->assertEquals('<span>test</span>', $this
->renderObjectWithTwig($variable));
}
protected function renderObjectWithTwig($variable) {
$renderer = \Drupal::service('renderer');
$context = new RenderContext();
return $renderer
->executeInRenderContext($context, function () use ($renderer, $variable) {
$elements = [
'#type' => 'inline_template',
'#template' => '{%- if variable is not empty -%}<span>{{ variable }}</span>{%- endif -%}',
'#context' => array(
'variable' => $variable,
),
];
return $renderer
->render($elements);
});
}
}
class SafeMarkupTestMarkup implements MarkupInterface {
use MarkupTrait;
public static function create($string) {
$object = new static();
$object->string = $string;
return $object;
}
}