Version 1
[yaffs-website] / web / modules / contrib / ctools / src / Plugin / Relationship / TypedDataRelationship.php
1 <?php
2
3 namespace Drupal\ctools\Plugin\Relationship;
4
5
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;
15
16 /**
17  * @Relationship(
18  *   id = "typed_data_relationship",
19  *   deriver = "\Drupal\ctools\Plugin\Deriver\TypedDataRelationshipDeriver"
20  * )
21  */
22 class TypedDataRelationship extends RelationshipBase {
23
24   /**
25    * {@inheritdoc}
26    */
27   public function getRelationship() {
28     $plugin_definition = $this->getPluginDefinition();
29
30     $data_type = $plugin_definition['data_type'];
31     $context_definition = new ContextDefinition($data_type, $plugin_definition['label']);
32     $context_value = NULL;
33
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();
41     }
42
43     $context_definition->setDefaultValue($context_value);
44     return new Context($context_definition, $context_value);
45   }
46
47   public function getName() {
48     return $this->getPluginDefinition()['property_name'];
49   }
50
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();
59     }
60     if ($data instanceof DataReferenceInterface) {
61       $data = $data->getTarget();
62     }
63     return $data;
64   }
65
66   protected function getMainPropertyName(FieldItemInterface $data) {
67     return $data->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
68   }
69
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();
75   }
76
77 }