function PluginExistsConstraintValidatorTest::testValidation

Same name in other branches
  1. 10 core/tests/Drupal/KernelTests/Core/Plugin/PluginExistsConstraintValidatorTest.php \Drupal\KernelTests\Core\Plugin\PluginExistsConstraintValidatorTest::testValidation()

Tests validation of plugin existence.

File

core/tests/Drupal/KernelTests/Core/Plugin/PluginExistsConstraintValidatorTest.php, line 31

Class

PluginExistsConstraintValidatorTest
@group Plugin @group Validation

Namespace

Drupal\KernelTests\Core\Plugin

Code

public function testValidation() : void {
    $definition = DataDefinition::create('string')->addConstraint('PluginExists', 'plugin.manager.action');
    // An existing action plugin should pass validation.
    $data = $this->container
        ->get('typed_data_manager')
        ->create($definition);
    $data->setValue('action_test_save_entity');
    $this->assertCount(0, $data->validate());
    // It should also pass validation if we check for an interface it actually
    // implements.
    $definition->setConstraints([
        'PluginExists' => [
            'manager' => 'plugin.manager.action',
            'interface' => ActionInterface::class,
        ],
    ]);
    $this->assertCount(0, $data->validate());
    // A non-existent plugin should be invalid, regardless of interface.
    $data->setValue('non_existent_plugin');
    $violations = $data->validate();
    $this->assertCount(1, $violations);
    $this->assertSame("The 'non_existent_plugin' plugin does not exist.", (string) $violations->get(0)
        ->getMessage());
    // An existing plugin that doesn't implement the specified interface should
    // raise an error.
    $definition->setConstraints([
        'PluginExists' => [
            'manager' => 'plugin.manager.action',
            'interface' => MenuInterface::class,
        ],
    ]);
    $data->setValue('action_test_save_entity');
    $violations = $data->validate();
    $this->assertCount(1, $violations);
    $this->assertSame("The 'action_test_save_entity' plugin must implement or extend " . MenuInterface::class . '.', (string) $violations->get(0)
        ->getMessage());
    // No validation is attempted on a NULL value.
    $data->setValue(NULL);
    $violations = $data->validate();
    $this->assertCount(0, $violations);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.