3 namespace Drupal\KernelTests\Core\Plugin\Condition;
5 use Drupal\Core\Plugin\Context\Context;
6 use Drupal\Core\Plugin\Context\EntityContext;
7 use Drupal\Core\Plugin\Context\EntityContextDefinition;
8 use Drupal\KernelTests\KernelTestBase;
9 use Drupal\node\Entity\Node;
10 use Drupal\node\Entity\NodeType;
13 * Tests a condition with optional context.
15 * @group condition_test
17 class OptionalContextConditionTest extends KernelTestBase {
22 public static $modules = ['system', 'user', 'condition_test', 'node'];
25 * Tests with both contexts mapped to the same user.
27 public function testContextMissing() {
28 /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
29 $condition = \Drupal::service('plugin.manager.condition')
30 ->createInstance('condition_test_optional_context')
34 \Drupal::service('context.handler')->applyContextMapping($condition, []);
35 $this->assertTrue($condition->execute());
39 * Tests with both contexts mapped to the same user.
41 public function testContextNoValue() {
42 /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
43 $condition = \Drupal::service('plugin.manager.condition')
44 ->createInstance('condition_test_optional_context')
48 $definition = EntityContextDefinition::fromEntityTypeId('node');
49 $contexts['node'] = (new Context($definition));
50 \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
51 $this->assertTrue($condition->execute());
55 * Tests with both contexts mapped to the same user.
57 public function testContextAvailable() {
58 NodeType::create(['type' => 'example', 'name' => 'Example'])->save();
59 /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
60 $condition = \Drupal::service('plugin.manager.condition')
61 ->createInstance('condition_test_optional_context')
65 $node = Node::create(['type' => 'example']);
66 $contexts['node'] = EntityContext::fromEntity($node);
67 \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
68 $this->assertFalse($condition->execute());