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

/**
 * @file
 * Contains \Drupal\text\Tests\Formatter\TextFormatterTest.
 */

namespace Drupal\text\Tests\Formatter;

10
use Drupal\field\Entity\FieldConfig;
11
use Drupal\filter\Entity\FilterFormat;
12
use Drupal\system\Tests\Entity\EntityUnitTestBase;
13
use Drupal\field\Entity\FieldStorageConfig;
14 15

/**
16 17 18
 * Tests the text formatters functionality.
 *
 * @group text
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 */
class TextFormatterTest extends EntityUnitTestBase {

  /**
   * The entity type used in this test.
   *
   * @var string
   */
  protected $entityType = 'entity_test';

  /**
   * The bundle used in this test.
   *
   * @var string
   */
  protected $bundle = 'entity_test';

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('text');

  /**
   * {@inheritdoc}
   */
46
  protected function setUp() {
47 48
    parent::setUp();

49
    FilterFormat::create(array(
50 51 52 53 54 55 56 57 58 59
      'format' => 'my_text_format',
      'name' => 'My text format',
      'filters' => array(
        'filter_autop' => array(
          'module' => 'filter',
          'status' => TRUE,
        ),
      ),
    ))->save();

60
    FieldStorageConfig::create(array(
61
      'field_name' => 'formatted_text',
62 63 64 65
      'entity_type' => $this->entityType,
      'type' => 'text',
      'settings' => array(),
    ))->save();
66
    FieldConfig::create([
67 68
      'entity_type' => $this->entityType,
      'bundle' => $this->bundle,
69 70
      'field_name' => 'formatted_text',
      'label' => 'Filtered text',
71
    ])->save();
72 73 74 75 76 77 78 79 80 81 82 83 84
  }

  /**
   * Tests all text field formatters.
   */
  public function testFormatters() {
    $formatters = array(
      'text_default',
      'text_trimmed',
      'text_summary_or_trimmed',
    );

    // Create the entity to be referenced.
85
    $entity = entity_create($this->entityType, array('name' => $this->randomMachineName()));
86
    $entity->formatted_text = array(
87 88 89 90 91 92
      'value' => 'Hello, world!',
      'format' => 'my_text_format',
    );
    $entity->save();

    foreach ($formatters as $formatter) {
93 94
      // Verify the text field formatter's render array.
      $build = $entity->get('formatted_text')->view(array('type' => $formatter));
95
      \Drupal::service('renderer')->renderRoot($build[0]);
96
      $this->assertEqual($build[0]['#markup'], "<p>Hello, world!</p>\n");
97
      $this->assertEqual($build[0]['#cache']['tags'], FilterFormat::load('my_text_format')->getCacheTags(), format_string('The @formatter formatter has the expected cache tags when formatting a formatted text field.', array('@formatter' => $formatter)));
98 99 100 101
    }
  }

}