copyNode method

TreeElement copyNode(
  1. TreeElement source,
  2. TreeReference to
)

Copies source (without templates) to to, which may be unbound in its last step to append a new instance.

Implementation

TreeElement copyNode(TreeElement source, TreeReference to) {
  if (!to.isAbsolute) {
    throw InvalidReferenceException(
      'Destination reference must be absolute for copying',
      to,
    );
  }
  final destinationName = to.lastName;
  var destinationMultiplicity = to.lastMultiplicity;
  final parentRef = to.parentRef!;
  final parent = resolveReference(parentRef);
  if (parent == null) {
    throw InvalidReferenceException(
      'Null parent reference whle attempting to copy',
      parentRef,
    );
  }
  if (!parent.isChildable) {
    throw InvalidReferenceException(
      'Invalid Parent Node: cannot accept children.',
      parentRef,
    );
  }
  if (destinationMultiplicity == TreeReference.indexUnbound) {
    destinationMultiplicity = parent.childMultiplicity(destinationName);
  } else if (parent.getChild(destinationName, destinationMultiplicity) !=
      null) {
    throw InvalidReferenceException('Destination already exists!', to);
  }
  final destination = source.deepCopy(includeTemplates: false)
    ..name = destinationName
    ..multiplicity = destinationMultiplicity;
  parent.addChild(destination);
  return destination;
}