You are here

class LoopTest in Rules 8.3

Test Rules execution with the loop plugin.

@group Rules

Hierarchy

Expanded class hierarchy of LoopTest

File

tests/src/Unit/Integration/Engine/LoopTest.php, line 19

Namespace

Drupal\Tests\rules\Unit\Integration\Engine
View source
class LoopTest extends RulesEntityIntegrationTestBase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() : void {
    parent::setUp();
    $this
      ->enableModule('node');
  }

  /**
   * Tests that list items in the loop can be used during execution.
   */
  public function testListItemUsage() {

    // The rule contains a list of strings that will be concatenated into one
    // variable.
    $rule = $this->rulesExpressionManager
      ->createRule();
    $rule
      ->addAction('rules_variable_add', ContextConfig::create()
      ->setValue('type', 'string')
      ->setValue('value', '')
      ->provideAs('variable_added', 'result'));
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'string_list',
    ]);
    $loop
      ->addAction('rules_data_set', ContextConfig::create()
      ->map('data', 'result')
      ->setValue('value', '{{result}} {{list_item}}')
      ->process('value', 'rules_tokens'));
    $rule
      ->addExpressionObject($loop);
    $result = RulesComponent::create($rule)
      ->addContextDefinition('string_list', ContextDefinition::create('string')
      ->setMultiple())
      ->provideContext('result')
      ->setContextValue('string_list', [
      'Hello',
      'world',
      'this',
      'is',
      'the',
      'loop',
    ])
      ->execute();
    $this
      ->assertEquals(' Hello world this is the loop', $result['result']);
  }

  /**
   * Tests that list items can be renamed for usage in nested loops.
   */
  public function testListItemRenaming() {

    // The rule contains a list of strings that will be concatenated into one
    // variable.
    $rule = $this->rulesExpressionManager
      ->createRule();
    $rule
      ->addAction('rules_variable_add', ContextConfig::create()
      ->setValue('type', 'string')
      ->setValue('value', '')
      ->provideAs('variable_added', 'result'));
    $outer_loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'outer_list',
      'list_item' => 'outer_item',
    ]);
    $outer_loop
      ->addAction('rules_data_set', ContextConfig::create()
      ->map('data', 'result')
      ->setValue('value', '{{result}} {{outer_item}}')
      ->process('value', 'rules_tokens'));
    $inner_loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'inner_list',
      'list_item' => 'inner_item',
    ]);
    $inner_loop
      ->addAction('rules_data_set', ContextConfig::create()
      ->map('data', 'result')
      ->setValue('value', '{{result}} {{inner_item}}')
      ->process('value', 'rules_tokens'));
    $outer_loop
      ->addExpressionObject($inner_loop);
    $rule
      ->addExpressionObject($outer_loop);
    $result = RulesComponent::create($rule)
      ->addContextDefinition('outer_list', ContextDefinition::create('string')
      ->setMultiple())
      ->addContextDefinition('inner_list', ContextDefinition::create('string')
      ->setMultiple())
      ->provideContext('result')
      ->setContextValue('outer_list', [
      'Outer 1',
      'Outer 2',
    ])
      ->setContextValue('inner_list', [
      'Inner 1',
      'Inner 2',
      'Inner 3',
    ])
      ->execute();
    $this
      ->assertEquals(' Outer 1 Inner 1 Inner 2 Inner 3 Outer 2 Inner 1 Inner 2 Inner 3', $result['result']);
  }

  /**
   * Tests that a list can be chosen with a property path selector.
   */
  public function testPropertyPathList() {
    $rule = $this->rulesExpressionManager
      ->createRule();
    $rule
      ->addAction('rules_variable_add', ContextConfig::create()
      ->setValue('type', 'string')
      ->setValue('value', '')
      ->provideAs('variable_added', 'result'));
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'node.field_text',
    ]);
    $loop
      ->addAction('rules_data_set', ContextConfig::create()
      ->map('data', 'result')
      ->setValue('value', '{{result}} {{list_item}}')
      ->process('value', 'rules_tokens'));
    $rule
      ->addExpressionObject($loop);

    // Create a fake field for the fake node for testing.
    $list_definition = $this->typedDataManager
      ->createListDataDefinition('string');
    $field_text = new FieldItemList($list_definition);
    $field_text
      ->setValue([
      'Hello',
      'world',
      'this',
      'is',
      'the',
      'loop',
    ]);
    $node = $this
      ->prophesizeEntity(NodeInterface::class);
    $node
      ->get('field_text')
      ->willReturn($field_text);

    // We cannot use EntityDataDefinitionInterface here because the context
    // system in core violates the interface and relies on the actual class.
    // @see https://www.drupal.org/node/2660216
    $node_definition = $this
      ->prophesize(EntityDataDefinition::class);
    $node_definition
      ->getPropertyDefinition("field_text")
      ->willReturn($list_definition);
    $context_definition = $this
      ->getContextDefinitionFor('entity:node', $node_definition);
    $component = RulesComponent::create($rule)
      ->addContextDefinition('node', $context_definition)
      ->provideContext('result')
      ->setContextValue('node', $node
      ->reveal());
    $violations = $component
      ->checkIntegrity();
    $this
      ->assertEquals(0, iterator_count($violations));
    $result = $component
      ->execute();
    $this
      ->assertEquals(' Hello world this is the loop', $result['result']);
  }

  /**
   * Test the integrity check for loop item names that conflict with others.
   */
  public function testItemNameConflict() {
    $rule = $this->rulesExpressionManager
      ->createRule();
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'string_list',
      'list_item' => 'existing_name',
    ]);
    $rule
      ->addExpressionObject($loop);
    $violations = RulesComponent::create($rule)
      ->addContextDefinition('string_list', ContextDefinition::create('string')
      ->setMultiple())
      ->addContextDefinition('existing_name', ContextDefinition::create('string'))
      ->checkIntegrity();
    $this
      ->assertEquals(1, iterator_count($violations));
    $this
      ->assertEquals('List item name <em class="placeholder">existing_name</em> conflicts with an existing variable.', (string) $violations[0]
      ->getMessage());
  }

  /**
   * Tests that the specified list variable exists in the execution state.
   */
  public function testListExists() {
    $rule = $this->rulesExpressionManager
      ->createRule();
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'unknown_list',
    ]);
    $rule
      ->addExpressionObject($loop);
    $violations = RulesComponent::create($rule)
      ->checkIntegrity();
    $this
      ->assertEquals(1, iterator_count($violations));

    // The Exception message part of the output should be HTML-escaped.
    $this
      ->assertEquals("List variable <em class=\"placeholder\">unknown_list</em> does not exist. Unable to get variable &#039;unknown_list&#039;; it is not defined.", (string) $violations[0]
      ->getMessage());
  }

  /**
   * Tests that a loop must have a list configured.
   */
  public function testMissingList() {
    $rule = $this->rulesExpressionManager
      ->createRule();

    // Empty loop configuration, 'list' is missing.
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', []);
    $rule
      ->addExpressionObject($loop);
    $violations = RulesComponent::create($rule)
      ->checkIntegrity();
    $this
      ->assertEquals(1, iterator_count($violations));
    $this
      ->assertEquals('List variable is missing.', (string) $violations[0]
      ->getMessage());
  }

  /**
   * Tests that a variable used in an action within the loop exists.
   */
  public function testWrongVariableInAction() {
    $rule = $this->rulesExpressionManager
      ->createRule();
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'string_list',
    ]);
    $loop
      ->addAction('rules_test_string', ContextConfig::create()
      ->map('text', 'unknown_variable'));
    $rule
      ->addExpressionObject($loop);
    $violations = RulesComponent::create($rule)
      ->addContextDefinition('string_list', ContextDefinition::create('string')
      ->setMultiple())
      ->checkIntegrity();
    $this
      ->assertEquals(1, iterator_count($violations));

    // The Exception message part of the output should be HTML-escaped.
    $this
      ->assertEquals("Data selector <em class=\"placeholder\">unknown_variable</em> for context <em class=\"placeholder\">Text to concatenate</em> is invalid. Unable to get variable &#039;unknown_variable&#039;; it is not defined.", (string) $violations[0]
      ->getMessage());
  }

  /**
   * Tests that the data type used to loop over is a list.
   */
  public function testInvalidListType() {
    $rule = $this->rulesExpressionManager
      ->createRule();
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'string_variable',
    ]);
    $rule
      ->addExpressionObject($loop);
    $violations = RulesComponent::create($rule)
      ->addContextDefinition('string_variable', ContextDefinition::create('string'))
      ->checkIntegrity();
    $this
      ->assertEquals(1, iterator_count($violations));
    $this
      ->assertEquals('The data type of list variable <em class="placeholder">string_variable</em> is not a list.', (string) $violations[0]
      ->getMessage());
  }

  /**
   * Tests that the loop list item variable is not available after the loop.
   */
  public function testOutOfScopeVariable() {
    $rule = $this->rulesExpressionManager
      ->createRule();
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'string_list',
    ]);
    $rule
      ->addExpressionObject($loop);
    $rule
      ->addAction('rules_test_string', ContextConfig::create()
      ->map('text', 'list_item'));
    $violations = RulesComponent::create($rule)
      ->addContextDefinition('string_list', ContextDefinition::create('string')
      ->setMultiple())
      ->checkIntegrity();
    $this
      ->assertEquals(1, iterator_count($violations));

    // The Exception message part of the output should be HTML-escaped.
    $this
      ->assertEquals("Data selector <em class=\"placeholder\">list_item</em> for context <em class=\"placeholder\">Text to concatenate</em> is invalid. Unable to get variable &#039;list_item&#039;; it is not defined.", (string) $violations[0]
      ->getMessage());
  }

  /**
   * Tests that the loop list item variable is not available after the loop.
   */
  public function testOutOfScopeVariableExecution() {

    // Set the expected exception class and message.
    $this
      ->expectException(EvaluationException::class);
    $this
      ->expectExceptionMessage("Unable to get variable 'list_item'; it is not defined.");
    $rule = $this->rulesExpressionManager
      ->createRule();
    $loop = $this->rulesExpressionManager
      ->createInstance('rules_loop', [
      'list' => 'string_list',
    ]);
    $rule
      ->addExpressionObject($loop);
    $rule
      ->addAction('rules_test_string', ContextConfig::create()
      ->map('text', 'list_item'));
    RulesComponent::create($rule)
      ->addContextDefinition('string_list', ContextDefinition::create('string')
      ->setMultiple())
      ->setContextValue('string_list', [
      'one',
      'two',
    ])
      ->execute();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
LoopTest::setUp protected function Overrides RulesEntityIntegrationTestBase::setUp
LoopTest::testInvalidListType public function Tests that the data type used to loop over is a list.
LoopTest::testItemNameConflict public function Test the integrity check for loop item names that conflict with others.
LoopTest::testListExists public function Tests that the specified list variable exists in the execution state.
LoopTest::testListItemRenaming public function Tests that list items can be renamed for usage in nested loops.
LoopTest::testListItemUsage public function Tests that list items in the loop can be used during execution.
LoopTest::testMissingList public function Tests that a loop must have a list configured.
LoopTest::testOutOfScopeVariable public function Tests that the loop list item variable is not available after the loop.
LoopTest::testOutOfScopeVariableExecution public function Tests that the loop list item variable is not available after the loop.
LoopTest::testPropertyPathList public function Tests that a list can be chosen with a property path selector.
LoopTest::testWrongVariableInAction public function Tests that a variable used in an action within the loop exists.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
RulesEntityIntegrationTestBase::$entityAccess protected property The mocked entity access handler.
RulesEntityIntegrationTestBase::$fieldTypeManager protected property The field type manager.
RulesEntityIntegrationTestBase::$languageManager protected property The language manager mock.
RulesEntityIntegrationTestBase::getContextDefinitionFor protected function Helper to mock a context definition with a mocked data definition.
RulesIntegrationTestBase::$actionManager protected property
RulesIntegrationTestBase::$cacheBackend protected property
RulesIntegrationTestBase::$classResolver protected property The class resolver mock for the typed data manager.
RulesIntegrationTestBase::$conditionManager protected property
RulesIntegrationTestBase::$container protected property The Drupal service container.
RulesIntegrationTestBase::$dataFetcher protected property The data fetcher service.
RulesIntegrationTestBase::$dataFilterManager protected property The data filter manager.
RulesIntegrationTestBase::$enabledModules protected property Array object keyed with module names and TRUE as value.
RulesIntegrationTestBase::$entityFieldManager protected property
RulesIntegrationTestBase::$entityTypeBundleInfo protected property
RulesIntegrationTestBase::$entityTypeManager protected property
RulesIntegrationTestBase::$logger protected property A mocked Rules logger.channel.rules_debug service. 6
RulesIntegrationTestBase::$messenger protected property The messenger service.
RulesIntegrationTestBase::$moduleHandler protected property
RulesIntegrationTestBase::$namespaces protected property All setup'ed namespaces.
RulesIntegrationTestBase::$placeholderResolver protected property The placeholder resolver service.
RulesIntegrationTestBase::$rulesDataProcessorManager protected property
RulesIntegrationTestBase::$rulesExpressionManager protected property
RulesIntegrationTestBase::$typedDataManager protected property
RulesIntegrationTestBase::constructModulePath protected function Determines the path to a module's class files.
RulesIntegrationTestBase::enableModule protected function Fakes the enabling of a module and adds its namespace for plugin loading.
RulesIntegrationTestBase::getTypedData protected function Returns a typed data object.
RulesIntegrationTestBase::prophesizeEntity protected function Helper method to mock irrelevant cache methods on entities.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.