96c8bac736c8247a4253b4783b0aaa65372680a7
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Plugin / Condition / OptionalContextConditionTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Plugin\Condition;
4
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;
10
11 /**
12  * Tests a condition with optional context.
13  *
14  * @group condition_test
15  */
16 class OptionalContextConditionTest extends KernelTestBase {
17
18   /**
19    * {@inheritdoc}
20    */
21   public static $modules = ['system', 'user', 'condition_test', 'node'];
22
23   /**
24    * Tests with both contexts mapped to the same user.
25    */
26   public function testContextMissing() {
27     /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
28     $condition = \Drupal::service('plugin.manager.condition')
29       ->createInstance('condition_test_optional_context')
30       ->setContextMapping([
31         'node' => 'node',
32       ]);
33     \Drupal::service('context.handler')->applyContextMapping($condition, []);
34     $this->assertTrue($condition->execute());
35   }
36
37   /**
38    * Tests with both contexts mapped to the same user.
39    */
40   public function testContextNoValue() {
41     /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
42     $condition = \Drupal::service('plugin.manager.condition')
43       ->createInstance('condition_test_optional_context')
44       ->setContextMapping([
45         'node' => 'node',
46       ]);
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());
51   }
52
53   /**
54    * Tests with both contexts mapped to the same user.
55    */
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')
61       ->setContextMapping([
62         'node' => 'node',
63       ]);
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());
69   }
70
71 }