summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/TypedData/DataReferenceBase.php
blob: a41b01c65df6fb95ca7f7d180c07cafcaf41035a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

namespace Drupal\Core\TypedData;

/**
 * Base class for typed data references.
 *
 * Data types based on this base class need to be named
 * "{TARGET_TYPE}_reference", whereas {TARGET_TYPE} is the referenced data type.
 * For example, an entity reference data type would have to be named
 * "entity_reference".
 * Beside that, implementing classes have to implement at least
 * \Drupal\Core\TypedData\DataReferenceInterface::getTargetIdentifier().
 *
 * @see \Drupal\Core\TypedData\DataReferenceDefinition
 */
abstract class DataReferenceBase extends TypedData implements DataReferenceInterface {

  /**
   * The referenced data.
   *
   * @var \Drupal\Core\TypedData\TypedDataInterface
   */
  protected $target;

  /**
   * {@inheritdoc}
   */
  public function getTarget() {
    return $this->target;
  }

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    if ($target = $this->getTarget()) {
      return $target->getValue();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($value, $notify = TRUE) {
    $this->target = $this->getTypedDataManager()->create($this->definition->getTargetDefinition(), $value);
    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getString() {
    return (string) $this->getType() . ':' . $this->getTargetIdentifier();
  }

}