ContextHandlerTest.php in Drupal 10
File
core/tests/Drupal/KernelTests/Core/Plugin/ContextHandlerTest.php
View source
<?php
namespace Drupal\KernelTests\Core\Plugin;
use Drupal\Core\Plugin\Context\ContextHandler;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginTrait;
use Drupal\Core\Plugin\PluginBase;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
class ContextHandlerTest extends KernelTestBase {
protected static $modules = [
'entity_test',
'user',
];
public function testApplyContextMapping() {
$entity = EntityTest::create([]);
$context_definition = EntityContextDefinition::fromEntity($entity);
$context = EntityContext::fromEntity($entity);
$definition = [
'context_definitions' => [
'a_context_id' => $context_definition,
],
];
$plugin = new TestContextAwarePlugin([], 'test_plugin_id', $definition);
(new ContextHandler())
->applyContextMapping($plugin, [
'a_context_id' => $context,
]);
$result = $plugin
->getContext('a_context_id');
$this
->assertInstanceOf(EntityContext::class, $result);
$this
->assertSame($context, $result);
}
public function testApplyContextMappingAlreadyApplied() {
$entity = EntityTest::create([]);
$context_definition = EntityContextDefinition::fromEntity($entity);
$context = EntityContext::fromEntity($entity);
$definition = [
'context_definitions' => [
'a_context_id' => $context_definition,
],
];
$plugin = new TestContextAwarePlugin([], 'test_plugin_id', $definition);
$plugin
->setContext('a_context_id', $context);
(new ContextHandler())
->applyContextMapping($plugin, []);
$result = $plugin
->getContext('a_context_id');
$this
->assertInstanceOf(EntityContext::class, $result);
$this
->assertSame($context, $result);
}
}
class TestContextAwarePlugin extends PluginBase implements ContextAwarePluginInterface {
use ContextAwarePluginTrait;
}