Version 1
[yaffs-website] / web / core / lib / Drupal / Core / TypedData / DataReferenceDefinition.php
1 <?php
2
3 namespace Drupal\Core\TypedData;
4
5 /**
6  * A typed data definition class for defining references.
7  *
8  * Note that this definition class assumes that the data type for referencing
9  * a certain target type is named "{TARGET_TYPE}_reference".
10  *
11  * @see \Drupal\Core\TypedData\DataReferenceBase
12  */
13 class DataReferenceDefinition extends DataDefinition implements DataReferenceDefinitionInterface {
14
15   /**
16    * @var \Drupal\Core\TypedData\DataDefinitionInterface
17    */
18   protected $targetDefinition;
19
20   /**
21    * Creates a new data reference definition.
22    *
23    * @param string $target_data_type
24    *   The data type of the referenced data.
25    *
26    * @return static
27    */
28   public static function create($target_data_type) {
29     // This assumes implementations use a "TYPE_reference" naming pattern.
30     $definition = parent::create($target_data_type . '_reference');
31     return $definition->setTargetDefinition(\Drupal::typedDataManager()->createDataDefinition($target_data_type));
32   }
33
34   /**
35    * {@inheritdoc}
36    */
37   public static function createFromDataType($data_type) {
38     if (substr($data_type, -strlen('_reference')) != '_reference') {
39       throw new \InvalidArgumentException('Data type must be of the form "{TARGET_TYPE}_reference"');
40     }
41     // Cut of the _reference suffix.
42     return static::create(substr($data_type, 0, strlen($data_type) - strlen('_reference')));
43   }
44
45   /**
46    * {@inheritdoc}
47    */
48   public function getTargetDefinition() {
49     return $this->targetDefinition;
50   }
51
52   /**
53    * Sets the definition of the referenced data.
54    *
55    * @param \Drupal\Core\TypedData\DataDefinitionInterface $definition
56    *   The target definition to set.
57    *
58    * @return $this
59    */
60   public function setTargetDefinition(DataDefinitionInterface $definition) {
61     $this->targetDefinition = $definition;
62     return $this;
63   }
64
65 }