e0a4a09952e2ee6e36304dd37d3d18c7bd7a9ea1
[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\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;
11
12 /**
13  * Tests a condition with optional context.
14  *
15  * @group condition_test
16  */
17 class OptionalContextConditionTest extends KernelTestBase {
18
19   /**
20    * {@inheritdoc}
21    */
22   public static $modules = ['system', 'user', 'condition_test', 'node'];
23
24   /**
25    * Tests with both contexts mapped to the same user.
26    */
27   public function testContextMissing() {
28     /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
29     $condition = \Drupal::service('plugin.manager.condition')
30       ->createInstance('condition_test_optional_context')
31       ->setContextMapping([
32         'node' => 'node',
33       ]);
34     \Drupal::service('context.handler')->applyContextMapping($condition, []);
35     $this->assertTrue($condition->execute());
36   }
37
38   /**
39    * Tests with both contexts mapped to the same user.
40    */
41   public function testContextNoValue() {
42     /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
43     $condition = \Drupal::service('plugin.manager.condition')
44       ->createInstance('condition_test_optional_context')
45       ->setContextMapping([
46         'node' => 'node',
47       ]);
48     $definition = EntityContextDefinition::fromEntityTypeId('node');
49     $contexts['node'] = (new Context($definition));
50     \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
51     $this->assertTrue($condition->execute());
52   }
53
54   /**
55    * Tests with both contexts mapped to the same user.
56    */
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')
62       ->setContextMapping([
63         'node' => 'node',
64       ]);
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());
69   }
70
71 }