3 namespace Drupal\ctools\Plugin\Relationship;
6 use Drupal\Core\Field\FieldItemInterface;
7 use Drupal\Core\Field\TypedData\FieldItemDataDefinition;
8 use Drupal\Core\Plugin\Context\Context;
9 use Drupal\Core\Plugin\Context\ContextDefinition;
10 use Drupal\Core\Plugin\Context\ContextInterface;
11 use Drupal\Core\TypedData\DataReferenceInterface;
12 use Drupal\Core\TypedData\ListInterface;
13 use Drupal\ctools\Annotation\Relationship;
14 use Drupal\ctools\Plugin\RelationshipBase;
18 * id = "typed_data_relationship",
19 * deriver = "\Drupal\ctools\Plugin\Deriver\TypedDataRelationshipDeriver"
22 class TypedDataRelationship extends RelationshipBase {
27 public function getRelationship() {
28 $plugin_definition = $this->getPluginDefinition();
30 $data_type = $plugin_definition['data_type'];
31 $context_definition = new ContextDefinition($data_type, $plugin_definition['label']);
32 $context_value = NULL;
34 // If the 'base' context has a value, then get the property value to put on
35 // the context (otherwise, mapping hasn't occurred yet and we just want to
36 // return the context with the right definition and no value).
37 if ($this->getContext('base')->hasContextValue()) {
38 $data = $this->getData($this->getContext('base'));
39 $property = $this->getMainPropertyName($data);
40 $context_value = $data->get($property)->getValue();
43 $context_definition->setDefaultValue($context_value);
44 return new Context($context_definition, $context_value);
47 public function getName() {
48 return $this->getPluginDefinition()['property_name'];
51 protected function getData(ContextInterface $context) {
52 /** @var \Drupal\Core\TypedData\ComplexDataInterface $base */
53 $base = $context->getContextValue();
54 $name = $this->getPluginDefinition()['property_name'];
55 $data = $base->get($name);
56 // @todo add configuration to get N instead of first.
57 if ($data instanceof ListInterface) {
58 $data = $data->first();
60 if ($data instanceof DataReferenceInterface) {
61 $data = $data->getTarget();
66 protected function getMainPropertyName(FieldItemInterface $data) {
67 return $data->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
70 public function getRelationshipValue() {
71 $property = $this->getMainPropertyName();
72 /** @var \Drupal\Core\TypedData\ComplexDataInterface $data */
73 $data = $this->getRelationship()->getContextData();
74 $data->get($property)->getValue();