OptionalContextConditionTest.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\KernelTests\Core\Plugin\Condition;
  3. use Drupal\Core\Plugin\Context\Context;
  4. use Drupal\Core\Plugin\Context\ContextDefinition;
  5. use Drupal\KernelTests\KernelTestBase;
  6. use Drupal\node\Entity\Node;
  7. use Drupal\node\Entity\NodeType;
  8. /**
  9. * Tests a condition with optional context.
  10. *
  11. * @group condition_test
  12. */
  13. class OptionalContextConditionTest extends KernelTestBase {
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public static $modules = ['system', 'user', 'condition_test', 'node'];
  18. /**
  19. * Tests with both contexts mapped to the same user.
  20. */
  21. public function testContextMissing() {
  22. /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
  23. $condition = \Drupal::service('plugin.manager.condition')
  24. ->createInstance('condition_test_optional_context')
  25. ->setContextMapping([
  26. 'node' => 'node',
  27. ]);
  28. \Drupal::service('context.handler')->applyContextMapping($condition, []);
  29. $this->assertTrue($condition->execute());
  30. }
  31. /**
  32. * Tests with both contexts mapped to the same user.
  33. */
  34. public function testContextNoValue() {
  35. /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
  36. $condition = \Drupal::service('plugin.manager.condition')
  37. ->createInstance('condition_test_optional_context')
  38. ->setContextMapping([
  39. 'node' => 'node',
  40. ]);
  41. $definition = new ContextDefinition('entity:node');
  42. $contexts['node'] = (new Context($definition));
  43. \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
  44. $this->assertTrue($condition->execute());
  45. }
  46. /**
  47. * Tests with both contexts mapped to the same user.
  48. */
  49. public function testContextAvailable() {
  50. NodeType::create(['type' => 'example', 'name' => 'Example'])->save();
  51. /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
  52. $condition = \Drupal::service('plugin.manager.condition')
  53. ->createInstance('condition_test_optional_context')
  54. ->setContextMapping([
  55. 'node' => 'node',
  56. ]);
  57. $definition = new ContextDefinition('entity:node');
  58. $node = Node::create(['type' => 'example']);
  59. $contexts['node'] = new Context($definition, $node);
  60. \Drupal::service('context.handler')->applyContextMapping($condition, $contexts);
  61. $this->assertFalse($condition->execute());
  62. }
  63. }