View source
<?php
namespace Drupal\Tests\text\Kernel;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\field\Entity\FieldConfig;
use Drupal\filter\Entity\FilterFormat;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
class TextFormatterTest extends EntityKernelTestBase {
protected $entityType = 'entity_test';
protected $bundle = 'entity_test';
protected static $modules = [
'text',
];
protected function setUp() : void {
parent::setUp();
FilterFormat::create([
'format' => 'my_text_format',
'name' => 'My text format',
'filters' => [
'filter_autop' => [
'module' => 'filter',
'status' => TRUE,
],
],
])
->save();
FieldStorageConfig::create([
'field_name' => 'formatted_text',
'entity_type' => $this->entityType,
'type' => 'text',
'settings' => [],
])
->save();
FieldConfig::create([
'entity_type' => $this->entityType,
'bundle' => $this->bundle,
'field_name' => 'formatted_text',
'label' => 'Filtered text',
])
->save();
}
public function testFormatters() {
$formatters = [
'text_default',
'text_trimmed',
'text_summary_or_trimmed',
];
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'name' => $this
->randomMachineName(),
]);
$entity->formatted_text = [
'value' => 'Hello, world!',
'format' => 'my_text_format',
];
$entity
->save();
foreach ($formatters as $formatter) {
$build = $entity
->get('formatted_text')
->view([
'type' => $formatter,
]);
\Drupal::service('renderer')
->renderRoot($build[0]);
$this
->assertEquals("<p>Hello, world!</p>\n", $build[0]['#markup']);
$this
->assertEquals(FilterFormat::load('my_text_format')
->getCacheTags(), $build[0]['#cache']['tags'], new FormattableMarkup('The @formatter formatter has the expected cache tags when formatting a formatted text field.', [
'@formatter' => $formatter,
]));
}
}
}