3 namespace Drupal\KernelTests\Core\Plugin\Condition;
5 use Drupal\Core\Plugin\Context\Context;
6 use Drupal\Core\Plugin\Context\ContextDefinition;
7 use Drupal\KernelTests\KernelTestBase;
8 use Drupal\node\Entity\Node;
9 use Drupal\node\Entity\NodeType;
12 * Tests a condition with optional context.
14 * @group condition_test
16 class OptionalContextConditionTest extends KernelTestBase {
21 public static $modules = ['system', 'user', 'condition_test', 'node'];
24 * Tests with both contexts mapped to the same user.
26 public function testContextMissing() {
27 /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
28 $condition = \Drupal::service('plugin.manager.condition')
29 ->createInstance('condition_test_optional_context')
33 \Drupal::service('context.handler')->applyContextMapping($condition, []);
34 $this->assertTrue($condition->execute());
38 * Tests with both contexts mapped to the same user.
40 public function testContextNoValue() {
41 /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
42 $condition = \Drupal::service('plugin.manager.condition')
43 ->createInstance('condition_test_optional_context')
47 $definition = new ContextDefinition('entity:node');
48 $contexts['node'] = (new Context($definition));
49 \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
50 $this->assertTrue($condition->execute());
54 * Tests with both contexts mapped to the same user.
56 public function testContextAvailable() {
57 NodeType::create(['type' => 'example', 'name' => 'Example'])->save();
58 /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
59 $condition = \Drupal::service('plugin.manager.condition')
60 ->createInstance('condition_test_optional_context')
64 $definition = new ContextDefinition('entity:node');
65 $node = Node::create(['type' => 'example']);
66 $contexts['node'] = new Context($definition, $node);
67 \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
68 $this->assertFalse($condition->execute());