function CoreIntegrationTest::testGlobalContext

Tests using global context.

File

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

Class

CoreIntegrationTest
Test using Drupal core integration of Rules API.

Namespace

Drupal\Tests\rules\Kernel

Code

public function testGlobalContext() {
    $account = User::create([
        'name' => 'hubert',
    ]);
    $account->save();
    $this->container
        ->get('current_user')
        ->setAccount($account);
    $rule = $this->expressionManager
        ->createRule()
        ->addAction('rules_system_message', ContextConfig::create()->map('message', '@user.current_user_context:current_user.name.value')
        ->setValue('type', 'status'));
    $component = RulesComponent::create($rule);
    $this->assertEquals(0, $component->checkIntegrity()
        ->count());
    // Ensure the execution-state is aware of global context.
    $result = $component->getState()
        ->hasVariable('@user.current_user_context:current_user');
    $this->assertTrue($result);
    // Test asking for non-existing variables.
    $this->assertFalse($component->getState()
        ->hasVariable('@user.current_user_context:invalid'));
    $this->assertFalse($component->getState()
        ->hasVariable('@user.invalid_service'));
    $this->assertFalse($component->getState()
        ->hasVariable('invalid-var'));
    // Test using global context during execution.
    $component->execute();
    $messages = $this->messenger
        ->all();
    $this->assertEquals((string) $messages[MessengerInterface::TYPE_STATUS][0], 'hubert');
}