function EventPropertyAccessTest::testEventProperties

Tests that all event properties may be accessed.

Properties declared in the MODULENAME.rules.events.yml metadata are accessed by the \Drupal\rules\EventSubscriber\GenericEventSubscriber. If these properties are not present or not visible to the event subscriber, executing a Rule that uses these properties will throw an exception.

@dataProvider provideTestEvent

Parameters

string $event_name: The Plugin ID of the event being tested.

object $event: The event object being tested. In Drupal 9 this will be a \Symfony\Component\EventDispatcher\Event, In Drupal 10 this will be a \Symfony\Contracts\EventDispatcher\Event.

File

tests/src/Kernel/EventPropertyAccessTest.php, line 57

Class

EventPropertyAccessTest
Tests that Rules can use and access the properties of any Events.

Namespace

Drupal\Tests\rules\Kernel

Code

public function testEventProperties($event_name, object $event) : void {
    $rule = $this->expressionManager
        ->createRule();
    $rule->addCondition('rules_test_true');
    $rule->addAction('rules_test_debug_log', ContextConfig::create()->map('message', 'publicProperty'));
    $rule->addAction('rules_test_debug_log', ContextConfig::create()->map('message', 'protectedProperty'));
    $rule->addAction('rules_test_debug_log', ContextConfig::create()->map('message', 'privateProperty'));
    $config_entity = $this->storage
        ->create([
        'id' => 'test_event_rule',
        'events' => [
            [
                'event_name' => $event_name,
            ],
        ],
        'expression' => $rule->getConfiguration(),
    ]);
    $config_entity->save();
    // The logger instance has changed, refresh it.
    $this->logger = $this->container
        ->get('logger.channel.rules_debug');
    $this->logger
        ->addLogger($this->debugLog);
    $dispatcher = $this->container
        ->get('event_dispatcher');
    // Remove all the listeners except Rules before triggering an event.
    $listeners = $dispatcher->getListeners(KernelEvents::REQUEST);
    foreach ($listeners as $listener) {
        if (empty($listener[1]) || $listener[1] != 'onRulesEvent') {
            $dispatcher->removeListener(KernelEvents::REQUEST, $listener);
        }
    }
    // Manually trigger the initialization event.
    $dispatcher->dispatch($event, $event_name);
    // Test that the action in the rule logged something.
    $this->assertRulesDebugLogEntryExists('public property', 0);
    $this->assertRulesDebugLogEntryExists('protected property', 1);
    $this->assertRulesDebugLogEntryExists('private property', 2);
}