DataReferenceBase.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Drupal\Core\TypedData;
  3. /**
  4. * Base class for typed data references.
  5. *
  6. * Data types based on this base class need to be named
  7. * "{TARGET_TYPE}_reference", whereas {TARGET_TYPE} is the referenced data type.
  8. * For example, an entity reference data type would have to be named
  9. * "entity_reference".
  10. * Beside that, implementing classes have to implement at least
  11. * \Drupal\Core\TypedData\DataReferenceInterface::getTargetIdentifier().
  12. *
  13. * @see \Drupal\Core\TypedData\DataReferenceDefinition
  14. */
  15. abstract class DataReferenceBase extends TypedData implements DataReferenceInterface {
  16. /**
  17. * The referenced data.
  18. *
  19. * @var \Drupal\Core\TypedData\TypedDataInterface
  20. */
  21. protected $target;
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function getTarget() {
  26. return $this->target;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function getValue() {
  32. if ($target = $this->getTarget()) {
  33. return $target->getValue();
  34. }
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function setValue($value, $notify = TRUE) {
  40. $this->target = $this->getTypedDataManager()->create($this->definition->getTargetDefinition(), $value);
  41. // Notify the parent of any changes.
  42. if ($notify && isset($this->parent)) {
  43. $this->parent->onChange($this->name);
  44. }
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function getString() {
  50. return (string) $this->getType() . ':' . $this->getTargetIdentifier();
  51. }
  52. }