DataReferenceDefinition.php 1.8 KB

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