3 namespace Drupal\Tests\field\Kernel\String;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
8 use Drupal\Core\Entity\FieldableEntityInterface;
9 use Drupal\entity_test\Entity\EntityTest;
10 use Drupal\field\Entity\FieldConfig;
11 use Drupal\field\Entity\FieldStorageConfig;
12 use Drupal\KernelTests\KernelTestBase;
15 * Tests the raw string formatter
19 class RawStringFormatterTest extends KernelTestBase {
26 public static $modules = ['field', 'text', 'entity_test', 'system', 'filter', 'user'];
31 protected $entityType;
44 * @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface
51 protected function setUp() {
54 // Configure the theme system.
55 $this->installConfig(['system', 'field']);
56 \Drupal::service('router.builder')->rebuild();
57 $this->installEntitySchema('entity_test');
59 $this->entityType = 'entity_test';
60 $this->bundle = $this->entityType;
61 $this->fieldName = Unicode::strtolower($this->randomMachineName());
63 $field_storage = FieldStorageConfig::create([
64 'field_name' => $this->fieldName,
65 'entity_type' => $this->entityType,
66 'type' => 'string_long',
68 $field_storage->save();
70 $instance = FieldConfig::create([
71 'field_storage' => $field_storage,
72 'bundle' => $this->bundle,
73 'label' => $this->randomMachineName(),
77 $this->display = entity_get_display($this->entityType, $this->bundle, 'default')
78 ->setComponent($this->fieldName, [
82 $this->display->save();
86 * Renders fields of a given entity with a given display.
88 * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
89 * The entity object with attached fields to render.
90 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
91 * The display to render the fields in.
94 * The rendered entity fields.
96 protected function renderEntityFields(FieldableEntityInterface $entity, EntityViewDisplayInterface $display) {
97 $content = $display->build($entity);
98 $content = $this->render($content);
103 * Tests string formatter output.
105 public function testStringFormatter() {
106 $value = $this->randomString();
107 $value .= "\n\n<strong>" . $this->randomString() . '</strong>';
108 $value .= "\n\n" . $this->randomString();
110 $entity = EntityTest::create([]);
111 $entity->{$this->fieldName}->value = $value;
113 // Verify that all HTML is escaped and newlines are retained.
114 $this->renderEntityFields($entity, $this->display);
115 $this->assertNoRaw($value);
116 $this->assertRaw(nl2br(Html::escape($value)));
118 // Verify the cache tags.
119 $build = $entity->{$this->fieldName}->view();
120 $this->assertTrue(!isset($build[0]['#cache']), 'The string formatter has no cache tags.');