Clone a node (with properties & customize)

@param  int          $sourceNode
@param  string|null  $sourceSchema optional, default: current schema
@return int          Cloned paragraph-id
196522
public function cloneNode( $sourceNode, $sourceSchema = null )
    {
        return $this->sql()
                    ->paragraph_clone( ( (string) $sourceSchema ) ?: null,
                                       (int)      $sourceNode );
    }
154258
public function copyFrom($sourceModel, $destinationModel)
    {
        $this->guardProviderNames($sourceModel);
        $this->guardProviderNames($destinationModel);

        $setters = $this->getSetters();

        if (empty($setters) || !\is_array($setters)) {
            throw new DcGeneralRuntimeException(
                \sprintf(
                    'No relationship setter defined from %s to %s.',
                    $this->getSourceName(),
                    $this->getDestinationName()
                )
            );
        }

        foreach ($setters as $setter) {
            if (!$this->isValidSetter($setter)) {
                throw new DcGeneralRuntimeException(
                    \sprintf(
                        'Invalid relationship setter entry, ensure it is an array containing only "to_field" and
                    one of "from_field", "value": %s',
                        \var_export($setter, true)
                    )
                );
            }

            if (isset($setter['from_field'])) {
                $destinationModel->setProperty($setter['to_field'], $sourceModel->getProperty($setter['to_field']));

                continue;
            }

            $destinationModel->setProperty($setter['to_field'], $setter['value']);
        }
    }
462595
public function addArray($parentNode, $sourceArray, $containerTag = null)
    {
        if (!count($sourceArray)) {
            return null;
        }

        // if there is a container tag specification,
        // the array is enclosed into it, majorly to
        // be used as a root element.
        if ($containerTag) {
            $sourceArray = array($containerTag => $sourceArray);
        }

        foreach ($sourceArray as $key => $value) {
            $newNode = $this->addNodeWithContent($parentNode, $key, $value);
        }

        // Return last node created.
        return $newNode;
    }
721652
public function compare(Schema $oldSchema, Schema $newSchema)
    {
        $createdTables = $this->getCreatedTables($oldSchema, $newSchema);
        $alteredTables = $this->getAlteredTables($oldSchema, $newSchema);
        $droppedTables = $this->getDroppedTables($oldSchema, $newSchema);

        $this->detectRenamedTables($createdTables, $droppedTables, $alteredTables);

        return new SchemaDiff(
            $oldSchema,
            $newSchema,
            $createdTables,
            $alteredTables,
            $droppedTables,
            $this->getCreatedSequences($oldSchema, $newSchema),
            $this->getDroppedSequences($oldSchema, $newSchema),
            $this->getCreatedViews($oldSchema, $newSchema),
            $this->getDroppedViews($oldSchema, $newSchema)
        );
    }
668772
private function loadSource(Model\Source $sourceModel, array $sourceData)
    {
        $sourceModel
        ->setId($sourceData['id'])
        ->setMethod(new Model\Method($sourceData['class'], $sourceData['method'], $sourceData['args']))
        ->setLazyLoading($sourceData['lazyLoading'])
        ->setSupplySeveralFields($sourceData['supplySeveralFields'])
        ->setOnFail($sourceData['onFail'])
        ->setExceptionClass($sourceData['exceptionClass'])
        ->setBadReturnValue($sourceData['badReturnValue'])
        ->setFallbackSourceId($sourceData['fallbackSourceId'])
        ->setDepends($sourceData['depends'])
        ;

        if (isset($sourceData['preprocessor']['method'])) {
            $sourceModel->addPreprocessor(
                new Model\Method(
                    $sourceData['preprocessor']['class'],
                    $sourceData['preprocessor']['method'],
                    $sourceData['preprocessor']['args']
                )
            );
        } elseif (isset($sourceData['preprocessors'])) {
            foreach ($sourceData['preprocessors'] as $preprocessor) {
                $sourceModel->addPreprocessor(
                    new Model\Method(
                        $preprocessor['class'],
                        $preprocessor['method'],
                        $preprocessor['args']
                    )
                );
            }
        }

        if (isset($sourceData['processor']['method'])) {
            $sourceModel->addProcessor(
                new Model\Method(
                    $sourceData['processor']['class'],
                    $sourceData['processor']['method'],
                    $sourceData['processor']['args']
                )
            );
        } elseif (isset($sourceData['processors'])) {
            foreach ($sourceData['processors'] as $processor) {
                $sourceModel->addProcessor(
                    new Model\Method(
                        $processor['class'],
                        $processor['method'],
                        $processor['args']
                    )
                );
            }
        }

        return $sourceModel;
    }
69856
def copy_node(node):
  """"""
  if not isinstance(node, gast.AST):
    return [copy_node(n) for n in node]
  new_node = copy.deepcopy(node)
  setattr(new_node, anno.ANNOTATION_FIELD,
          getattr(node, anno.ANNOTATION_FIELD, {}).copy())
  return new_node
960885
protected function copyNode(INode $source, ICollection $destinationParent, $destinationName = null)
    {
        if ('' === (string) $destinationName) {
            $destinationName = $source->getName();
        }

        if ($source instanceof IFile) {
            $data = $source->get();

            // If the body was a string, we need to convert it to a stream
            if (is_string($data)) {
                $stream = fopen('php://temp', 'r+');
                fwrite($stream, $data);
                rewind($stream);
                $data = $stream;
            }
            $destinationParent->createFile($destinationName, $data);
            $destination = $destinationParent->getChild($destinationName);
        } elseif ($source instanceof ICollection) {
            $destinationParent->createDirectory($destinationName);

            $destination = $destinationParent->getChild($destinationName);
            foreach ($source->getChildren() as $child) {
                $this->copyNode($child, $destination);
            }
        }
        if ($source instanceof IProperties && $destination instanceof IProperties) {
            $props = $source->getProperties([]);
            $propPatch = new PropPatch($props);
            $destination->propPatch($propPatch);
            $propPatch->commit();
        }
    }
177354
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        // Get nodes
        if (empty($options['sourceNode']) || !is_array($options['sourceNode'])) {
            throw new InvalidConfigurationException('No sourceNode given in options.', 1409078366);
        }
        $sourceNode = $this->nodeFactory->getNodeByArray($options['sourceNode']);
        $localNode = $deployment->getNode('localhost');
        $targetNode = $node;

        // Get shared paths
        $sourceSharedPath = $this->getSharedPathFromNode(
            $sourceNode,
            $deployment,
            $options['sourceNodeOptions'],
            $application
        );
        $localSharedPath = $deployment->getWorkspacePath($application).'_shared/';
        $targetSharedPath = $this->getSharedPathFromNode($node, $deployment, $options, $application);

        // maybe we should change this behaviour ...
        if ($targetNode->isLocalhost() === true || $sourceNode->isLocalhost() === true) {
            // sync direct
            $this->sync($sourceNode, $sourceSharedPath, $targetNode, $targetSharedPath, $deployment, $options);
        } else {
            // cached
            $this->sync($sourceNode, $sourceSharedPath, $localNode, $localSharedPath, $deployment, $options);
            $this->sync($localNode, $localSharedPath, $targetNode, $targetSharedPath, $deployment, $options);
        }
    }
262290
public function addSource(string $class, string $source): SchemaBuilder
    {
        if (!$this->hasSchema($class)) {
            throw new SchemaException("Unable to add source to '{$class}', class is unknown to ODM");
        }

        //See usage below
        $scope = [
            $this->getSchema($class)->getDatabase(),
            $this->getSchema($class)->getCollection()
        ];

        //Ensuring same source for all children classes from same collection
        foreach ($this->schemas as $schema) {
            if (isset($this->sources[$schema->getClass()])) {
                //Already set
                continue;
            }

            if (is_a($schema->getClass(), $class, true)) {
                //Only for entities from the same collection
                if ([$schema->getDatabase(), $schema->getCollection()] == $scope) {
                    $this->sources[$schema->getClass()] = $source;
                }
            }
        }

        return $this;
    }
1265745
public function createPageDraftFromOtherLanguage(Node $node, $sourceNodeTranslationId, $locale)
    {
        $user = $this->getAdminUser();

        $sourceNodeTranslation = $this->em->getRepository(NodeTranslation::class)->find($sourceNodeTranslationId);
        $sourceNodeVersion = $sourceNodeTranslation->getPublicNodeVersion();
        $sourcePage = $sourceNodeVersion->getRef($this->em);
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);

        /* @var NodeTranslation $nodeTranslation */
        $nodeTranslation = $this->em->getRepository(NodeTranslation::class)->addDraftNodeVersionFor($targetPage, $locale, $node, $user);
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();

        $this->eventDispatcher->dispatch(
            Events::RECOPY_PAGE_TRANSLATION,
            new RecopyPageTranslationNodeEvent(
                $node,
                $nodeTranslation,
                $nodeVersion,
                $targetPage,
                $sourceNodeTranslation,
                $sourceNodeVersion,
                $sourcePage,
                $sourceNodeTranslation->getLang()
            )
        );

        return $nodeTranslation;
    }
164493
protected function documentFragmentCreate($source, $charset = null)
    {
        $fake              = new DOMDocumentWrapper();
        $fake->contentType = $this->contentType;
        $fake->isXML       = $this->isXML;
        $fake->isHTML      = $this->isHTML;
        $fake->isXHTML     = $this->isXHTML;
        $fake->root        = $fake->document;
        if (!$charset) {
            $charset = $this->charset;
        }
        //	$fake->documentCreate($this->charset);
        if ($source instanceof DOMNODE && !($source instanceof DOMNODELIST)) {
            $source = array($source);
        }
        if (is_array($source) || $source instanceof DOMNODELIST) {
            // dom nodes
            // load fake document
            if (!$this->documentFragmentLoadMarkup($fake, $charset)) {
                return false;
            }
            $nodes = $fake->import($source);
            foreach ($nodes as $node)
                $fake->root->appendChild($node);
        } else {
            // string markup
            $this->documentFragmentLoadMarkup($fake, $charset, $source);
        }

        return $fake;
    }
362740
private static Node cloneNode(final Node dom) {
        final Transformer transformer;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
        } catch (final TransformerConfigurationException ex) {
            throw new IllegalStateException(
                "Could not create new Transformer to clone Node",
                ex
            );
        }
        final DOMSource source = new DOMSource(dom);
        try {
            final DOMResult result = new DOMResult();
            transformer.transform(source, result);
            return result.getNode();
        } catch (final TransformerException ex) {
            throw new IllegalArgumentException(
                String.format(
                    "Could not clone Node %s with Transformer %s",
                    source,
                    transformer
                ),
                ex
            );
        }
    }
765979
public Node cloneNode(boolean deep) {
        try {
            if (isXMLDoc == UNKNOWN_TYPE) isXMLDoc = getDocumentType();
            if (isXMLDoc == NON_XML) {
                throw new UnsupportedOperationException(
                    "Text document cannot be cloned");
            }
            // initialize a new doc owner node
            initClonedOwnerDoc();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("Internal Error:" + e);
        }
        if (deep) {
            for (NodeImpl n = (NodeImpl) getFirstChild(); n != null; n = (NodeImpl) n
                .getNextSibling()) {
                ownerDocCloned.appendChild(n.cloneNode(ownerDocCloned, true));
            }
        }
        return ownerDocCloned;
    }
1317406
public static function fromSourceWithClone( $src, $clone )
	{
		$result = new BufferedNodeIterator();
		$result->src = $clone ? $src->CloneInstance() : $src;
		$result->buffer = array();
		return $result;
	}
1082613
public function duplicateElementtype(Elementtype $sourceElementtype, $user)
    {
        $elementtype = clone $sourceElementtype;
        $uniqId = uniqid();

        foreach ($elementtype->getTitles() as $language => $title) {
            $elementtype->setTitle($language, $title.' - copy - '.$uniqId);
        }

        $elementtypeStructure = new ElementtypeStructure();

        $elementtype
            ->setId(null)
            ->setUniqueId($elementtype->getUniqueId().'-'.$uniqId)
            ->setRevision(1)
            ->setStructure($elementtypeStructure)
            ->setCreatedAt(new \DateTime())
            ->setCreateUser($user);

        $rii = new \RecursiveIteratorIterator($sourceElementtype->getStructure(), \RecursiveIteratorIterator::SELF_FIRST);

        $dsIdMap = [];
        foreach ($rii as $sourceNode) {
            /* @var $sourceNode ElementtypeStructureNode */
            if ($sourceNode->isReferenced()) {
                continue;
            }

            $node = clone $sourceNode;

            $dsIdMap[$sourceNode->getDsId()] = $dsId = UuidUtil::generate();

            $parentDsId = null;
            if (!$sourceNode->isRoot()) {
                $parentDsId = $dsIdMap[$sourceNode->getParentNode()->getDsId()];
            }

            $node
                ->setDsId($dsId)
                ->setParentDsId($parentDsId);

            $elementtypeStructure->addNode($node);
        }

        $mappings = $elementtype->getMappings();
        foreach ($mappings as $mappingIndex => $mapping) {
            foreach ($mapping['fields'] as $mappingFieldIndex => $mapingField) {
                if (isset($dsIdMap[$mapingField['dsId']])) {
                    $mappings[$mappingIndex]['fields'][$mappingFieldIndex]['dsId'] = $dsIdMap[$mapingField['dsId']];
                }
            }
        }
        $elementtype->setMappings($mappings);

        $this->elementtypeManager->updateElementtype($elementtype);

        return $elementtype;
    }
116814
protected function duplicateManyManyRelation($sourceObject, $destinationObject, $relation)
    {
        // Copy all components from source to destination
        $source = $sourceObject->getManyManyComponents($relation);
        $dest = $destinationObject->getManyManyComponents($relation);

        if ($source instanceof ManyManyList) {
            $extraFieldNames = $source->getExtraFields();
        } else {
            $extraFieldNames = [];
        }

        foreach ($source as $item) {
            // Merge extra fields
            $extraFields = [];
            foreach ($extraFieldNames as $fieldName => $fieldType) {
                $extraFields[$fieldName] = $item->getField($fieldName);
            }
            $dest->add($item, $extraFields);
        }
    }
960289
public function moveNode( $sourceNode, $position, $relatedNode )
    {
        $sourceNode = (int) $sourceNode;
        $sourceRoot = $this->getMapper()
                           ->findRootOf( $sourceNode );

        if ( empty( $sourceRoot ) ||
             ! $sourceRoot->isEditable() )
        {
            return array(
                'sourceNode'    => null,
                'position'      => $position,
                'relatedNode'   => $relatedNode,
                'success'       => false,
            );
        }

        $relatedNode = (int) $relatedNode;
        $relatedRoot = $this->getMapper()
                            ->findRootOf( $relatedNode );

        if ( empty( $relatedRoot ) ||
             ! $relatedRoot->isEditable() )
        {
            return array(
                'sourceNode'    => $sourceNode,
                'position'      => $position,
                'relatedNode'   => null,
                'success'       => false,
            );
        }

        $success = $this->getMapper()
                        ->moveNode( $sourceNode,
                                    strtolower( $position ),
                                    $relatedNode );

        return array(
            'sourceNode'    => $sourceNode,
            'position'      => $position,
            'relatedNode'   => $relatedNode,
            'success'       => (bool) $success,
        );
    }