You are here

public function ConfigurableEventHandlerTest::testConfigurableEventHandler in Rules 8.3

Tests ConfigurableEventHandlerEntityBundle.

Test that rules are triggered correctly based upon the fully qualified event name as well as the base event name.

@todo Add integrity check that node.field_integer is detected by Rules.

File

tests/src/Kernel/ConfigurableEventHandlerTest.php, line 84

Class

ConfigurableEventHandlerTest
Tests events with qualified name.

Namespace

Drupal\Tests\rules\Kernel

Code

public function testConfigurableEventHandler() {

  // Create rule1 with the 'rules_entity_presave:node--page' event.
  $rule1 = $this->expressionManager
    ->createRule();
  $rule1
    ->addAction('rules_test_debug_log', ContextConfig::create()
    ->map('message', 'node.field_integer.0.value'));
  $config_entity1 = $this->storage
    ->create([
    'id' => 'test_rule1',
  ]);
  $config_entity1
    ->set('events', [
    [
      'event_name' => 'rules_entity_presave:node--page',
    ],
  ]);
  $config_entity1
    ->set('expression', $rule1
    ->getConfiguration());
  $config_entity1
    ->save();

  // Create rule2 with the 'rules_entity_presave:node' event.
  $rule2 = $this->expressionManager
    ->createRule();
  $rule2
    ->addAction('rules_test_debug_log', ContextConfig::create()
    ->map('message', 'node.field_integer.1.value'));
  $config_entity2 = $this->storage
    ->create([
    'id' => 'test_rule2',
  ]);
  $config_entity2
    ->set('events', [
    [
      'event_name' => 'rules_entity_presave:node',
    ],
  ]);
  $config_entity2
    ->set('expression', $rule2
    ->getConfiguration());
  $config_entity2
    ->save();

  // The logger instance has changed, refresh it.
  $this->logger = $this->container
    ->get('logger.channel.rules_debug');
  $this->logger
    ->addLogger($this->debugLog);

  // Add node.field_integer.0.value to rules log message, read result.
  $this->node->field_integer
    ->setValue([
    '0' => 11,
    '1' => 22,
  ]);

  // Trigger node save.
  $entity_type_id = $this->node
    ->getEntityTypeId();
  $event = new EntityEvent($this->node, [
    $entity_type_id => $this->node,
    $entity_type_id . '_unchanged' => $this->node,
  ]);
  $event_dispatcher = $this->container
    ->get('event_dispatcher');
  $event_dispatcher
    ->dispatch("rules_entity_presave:{$entity_type_id}", $event);

  // Test that the action in the rule1 logged node value.
  $this
    ->assertRulesDebugLogEntryExists(11, 1);

  // Test that the action in the rule2 logged node value.
  $this
    ->assertRulesDebugLogEntryExists(22, 0);
}