You are here

public function FieldTest::testEntityFieldTokens in Token 8

Tests [entity:field_name] tokens.

File

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

Class

FieldTest
Tests field tokens.

Namespace

Drupal\Tests\token\Kernel

Code

public function testEntityFieldTokens() {

  // Create a node with a value in its fields and test its tokens.
  $entity = Node::create([
    'title' => 'Test node title',
    'type' => 'article',
    'test_field' => [
      'value' => 'foo',
      'format' => $this->testFormat
        ->id(),
    ],
    'test_list' => [
      'value1',
      'value2',
    ],
  ]);
  $entity
    ->save();
  $this
    ->assertTokens('node', [
    'node' => $entity,
  ], [
    'test_field' => Markup::create('foo'),
    'test_field:0' => Markup::create('foo'),
    'test_field:0:value' => 'foo',
    'test_field:value' => 'foo',
    'test_field:0:format' => $this->testFormat
      ->id(),
    'test_field:format' => $this->testFormat
      ->id(),
    'test_list:0' => Markup::create('value1'),
    'test_list:1' => Markup::create('value2'),
    'test_list:0:value' => Markup::create('value1'),
    'test_list:value' => Markup::create('value1'),
    'test_list:1:value' => Markup::create('value2'),
  ]);

  // Verify that no third token was generated for the list_string field.
  $this
    ->assertNoTokens('node', [
    'node' => $entity,
  ], [
    'test_list:2',
    'test_list:2:value',
  ]);

  // Test the test_list token metadata.
  $tokenService = \Drupal::service('token');
  $token_info = $tokenService
    ->getTokenInfo('node', 'test_list');
  $this
    ->assertEquals('test_list', $token_info['name']);
  $this
    ->assertEquals('token', $token_info['module']);
  $this
    ->assertEquals('list<node-test_list>', $token_info['type']);
  $typeInfo = $tokenService
    ->getTypeInfo('list<node-test_list>');
  $this
    ->assertEquals('List of test_list values', $typeInfo['name']);
  $this
    ->assertEquals('list<node-test_list>', $typeInfo['type']);

  // Create a node type that does not have test_field field.
  $node_type = NodeType::create([
    'type' => 'page',
  ]);
  $node_type
    ->save();
  $node_without_test_field = Node::create([
    'title' => 'Node without test_field',
    'type' => 'page',
  ]);
  $node_without_test_field
    ->save();

  // Ensure that trying to generate tokens for a non-existing field does not
  // throw an exception.
  $this
    ->assertNoTokens('node', [
    'node' => $node_without_test_field,
  ], [
    'test_field',
  ]);

  // Create a node without a value in the text field and test its token.
  $entity = Node::create([
    'title' => 'Test node title',
    'type' => 'article',
  ]);
  $entity
    ->save();
  $this
    ->assertNoTokens('node', [
    'node' => $entity,
  ], [
    'test_field',
  ]);
}