3 namespace Drupal\KernelTests\Core\Plugin;
5 use Drupal\Core\Plugin\Context\Context;
6 use Drupal\Core\Plugin\Context\ContextDefinition;
7 use Drupal\Core\TypedData\DataDefinition;
8 use Drupal\Core\TypedData\Plugin\DataType\StringData;
9 use Drupal\Core\TypedData\TypedDataManagerInterface;
10 use Drupal\KernelTests\KernelTestBase;
13 * Tests that contexts work properly with the typed data manager.
15 * @coversDefaultClass \Drupal\Core\Plugin\Context\Context
18 class ContextTypedDataTest extends KernelTestBase {
21 * Tests that contexts can be serialized.
23 public function testSerialize() {
24 $definition = new ContextDefinition('any');
25 $data_definition = DataDefinition::create('string');
26 $typed_data = new StringData($data_definition);
27 $typed_data->setValue('example string');
28 $context = new Context($definition, $typed_data);
29 // getContextValue() will cause the context to reference the typed data
31 $value = $context->getContextValue();
32 $context = serialize($context);
33 $context = unserialize($context);
34 $this->assertSame($value, $context->getContextValue());
38 * Tests that getting a context value does not throw fatal errors.
40 * This test ensures that the typed data manager is set correctly on the
43 * @covers ::getContextValue
45 public function testGetContextValue() {
46 $data_definition = DataDefinition::create('string');
47 $typed_data = new StringData($data_definition);
48 $typed_data->setValue('example string');
50 // Prepare a container that holds the typed data manager mock.
51 $typed_data_manager = $this->prophesize(TypedDataManagerInterface::class);
52 $typed_data_manager->getCanonicalRepresentation($typed_data)->will(function ($arguments) {
53 return $arguments[0]->getValue();
55 $this->container->set('typed_data_manager', $typed_data_manager->reveal());
57 $definition = new ContextDefinition('any');
58 $context = new Context($definition, $typed_data);
59 $value = $context->getContextValue();
60 $this->assertSame($value, $typed_data->getValue());