You are here

public function CoreIntegrationTest::testTokenFormattingReplacements in Rules 8.3

Tests that tokens used to format entity fields get replaced.

File

tests/src/Kernel/CoreIntegrationTest.php, line 170

Class

CoreIntegrationTest
Test using Drupal core integration of Rules API.

Namespace

Drupal\Tests\rules\Kernel

Code

public function testTokenFormattingReplacements() {
  $entity_type_manager = $this->container
    ->get('entity_type.manager');
  $entity_type_manager
    ->getStorage('node_type')
    ->create([
    'type' => 'page',
  ])
    ->save();
  $node = $entity_type_manager
    ->getStorage('node')
    ->create([
    'title' => 'test',
    'type' => 'page',
    // Set the created date to the first second in 1970.
    'created' => 1,
  ]);

  // Configure a simple rule with one action.
  $action = $this->expressionManager
    ->createInstance('rules_action', ContextConfig::create()
    ->map('message', 'message')
    ->map('type', 'type')
    ->process('message', 'rules_tokens')
    ->setConfigKey('action_id', 'rules_system_message')
    ->toArray());
  $rule = $this->expressionManager
    ->createRule()
    ->addExpressionObject($action);
  RulesComponent::create($rule)
    ->addContextDefinition('node', ContextDefinition::create('entity:node'))
    ->addContextDefinition('message', ContextDefinition::create('string'))
    ->addContextDefinition('type', ContextDefinition::create('string'))
    ->setContextValue('node', $node)
    ->setContextValue('message', "The node was created in the year {{ node.created.value | format_date('custom', 'Y') }}")
    ->setContextValue('type', 'status')
    ->execute();
  $messages = $this->messenger
    ->all();
  $this
    ->assertEquals((string) $messages[MessengerInterface::TYPE_STATUS][0], 'The node was created in the year 1970');
}