You are here

public function FieldTest::testFieldTokenInfo in Token 8

Tests the token metadata for a field token.

File

tests/src/Kernel/FieldTest.php, line 317

Class

FieldTest
Tests field tokens.

Namespace

Drupal\Tests\token\Kernel

Code

public function testFieldTokenInfo() {

  /** @var \Drupal\token\Token $tokenService */
  $tokenService = \Drupal::service('token');

  // Test the token info of the text field of the artcle content type.
  $token_info = $tokenService
    ->getTokenInfo('node', 'test_field');
  $this
    ->assertEquals('Test field', $token_info['name'], 'The token info name is correct.');
  $this
    ->assertEquals('Text (formatted) field.', $token_info['description'], 'The token info description is correct.');
  $this
    ->assertEquals('token', $token_info['module'], 'The token info module is correct.');

  // Now create two more content types that share the field but the last
  // of them sets a different label. This should show an alternative label
  // at the token info.
  $node_type = NodeType::create([
    'type' => 'article2',
  ]);
  $node_type
    ->save();
  $field = FieldConfig::create([
    'field_name' => 'test_field',
    'entity_type' => 'node',
    'bundle' => 'article2',
    'label' => 'Test field',
  ]);
  $field
    ->save();
  $node_type = NodeType::create([
    'type' => 'article3',
  ]);
  $node_type
    ->save();
  $field = FieldConfig::create([
    'field_name' => 'test_field',
    'entity_type' => 'node',
    'bundle' => 'article3',
    'label' => 'Different test field',
  ]);
  $field
    ->save();
  $token_info = $tokenService
    ->getTokenInfo('node', 'test_field');
  $this
    ->assertEquals('Test field', $token_info['name'], 'The token info name is correct.');
  $this
    ->assertEquals('Text (formatted) field. Also known as <em class="placeholder">Different test field</em>.', (string) $token_info['description'], 'When a field is used in several bundles with different labels, this is noted at the token info description.');
  $this
    ->assertEquals('token', $token_info['module'], 'The token info module is correct.');
  $this
    ->assertEquals('node-test_field', $token_info['type'], 'The field property token info type is correct.');

  // Test field property token info.
  $token_info = $tokenService
    ->getTokenInfo('node-test_field', 'value');
  $this
    ->assertEquals('Text', $token_info['name'], 'The field property token info name is correct.');

  // This particular field property description happens to be empty.
  $this
    ->assertEquals('', (string) $token_info['description'], 'The field property token info description is correct.');
  $this
    ->assertEquals('token', $token_info['module'], 'The field property token info module is correct.');
}