Make node $node a child of $newParent If this is an ordered tree,
the position should be the last

@param \BeeTree\Contracts\Node $node The moved or inserted node
@param \BeeTree\Contracts\Node $newParent The parent node
@return self
19180
public function makeChildOf(Node $node, Node $newParent)
    {

        // Collect some informations before the node is changed to correct
        // the nodes in its old position
        $nodeWasNew = !$node->exists;
        $oldParentId = $node->getParentId();
        $oldPosition = $node->getPosition();

        // Get new position
        $position = $this->getLastChildPosition($newParent);

        // Set the position of this node. Default is last position in new Parent
        $node[$this->getPositionName()] = $position;

        $this->performMakeChildOf($node, $node);

        // If the node existed correct the positions of the old parent
        if(!$nodeWasNew && $oldParentId){
            $this->decrementOrderAfter($oldParentId, $oldPosition);
        }

        return $this;

    }
530880
public function addNode(Node $child)
    {
        $this->children[] = $child;
        $child->setParent($this);

        return $this;
    }
226002
public function after()
    {
        $this->importNodes(\func_get_args(), function ($node, $imported_node) {
            if ($node->nextSibling) {
                $node->parentNode->insertBefore($imported_node, $node->nextSibling);
            } else { // node is last, so there is no next sibling to insert before
                $node->parentNode->appendChild($imported_node);
            }
        });

        return $this;
    }
141865
protected function insertBeforeChild(Node $child, Node $node) {
    $this->childCount++;
    $node->parent = $this;
    if ($child->previous === NULL) {
      $this->head = $node;
    }
    else {
      $child->previous->next = $node;
    }
    $node->previous = $child->previous;
    $node->next = $child;
    $child->previous = $node;
    return $this;
  }
812059
protected function performCreateChildOf(array $attributes, Node $parent)
    {

        $parentIdName = $this->getParentIdName();
        $rootIdName = $this->getRootIdName();

        $child = $this->make($attributes);
        $child[$parentIdName] = $parent->getId();
        $child[$rootIdName] = $parent[$rootIdName];

        $child->save();

        // Set in-memory relations
        $child->setParent($parent);
        $parent->addChild($child);

        return $child;

    }
184281
function(node) {
                var self = this;
                node.parent && node.remove();
                self.insert(node, self);
                self.remove();
                return self;
            }
1352255
public function placeAt(Sortable $movedNode, Sortable $newParent, $position)
    {
        // 1. movedNode.parentId = newDescendant.parentId, movedNode.position = MAX(newDescendant.position,1)
        // 2. removeFromSort(movedNode) like delete without delete
        // 2. UPDATE SET position = position+1 WHERE parentId = newAncestor.parentId
        //    AND position >= movedNode.position
        // 3. movedNode.save()

        $targetParentId = $newParent->getId();
        $targetPosition = $position;
        $oldParentId = $movedNode->getParentId();
        $oldPosition = $movedNode->getPosition();

        // Nothing to do
        if ($targetParentId == $oldParentId &&
            $targetPosition == $oldPosition &&
            $movedNode->exists) {
            return $this;
        }

        $movedNode[$this->getParentIdName()] = $targetParentId;
        $movedNode[$this->getPositionName()] = $targetPosition;

        // Remove node from old parent
        $this->decrementOrderAfter($oldParentId, $oldPosition);

        // Create space for new position
        $this->incrementOrderAfter($targetParentId, $targetPosition-1);

        $movedNode->save();

        return $this;

    }
287117
public function moveAsLastChildOf(NodeInterface $parentNode)
	{
		$this->validateAddingChildren($parentNode);

		$pos = $parentNode->getRightValue();
		$level = $parentNode->getLevel() + 1;
		$this->move($pos, $level);

		return $this;
	}
318594
public function reorder(TreeNodeInterface $node, TreeNodeInterface $beforeNode)
    {
        if ($beforeNode->getParentNode()->getId() !== $node->getParentNode()->getId()) {
            throw new InvalidNodeMoveException('Node and targetNode need to have the same parent.');
        }

        if ($node->getParentNode()->getSortMode() !== 'free') {
            return;
        }

        $sort = $beforeNode->getSort() + 1;

        $event = new ReorderNodeEvent($node, $sort);
        if ($this->dispatcher->dispatch(TreeEvents::BEFORE_REORDER_NODE, $event)->isPropagationStopped()) {
            return;
        }

        $updatesNodes = [];

        $currentSort = $sort + 1;
        foreach ($this->getChildren($node->getParentNode()) as $childNode) {
            if ($childNode->getSort() <= $sort) {
                $childNode->setSort($currentSort++);
                $updatesNodes[] = $childNode;
            }
        }

        $node->setSort($sort);
        $updateNodes[] = $node;

        $this->updateNodes($updateNodes);

        $event = new NodeEvent($node);
        $this->dispatcher->dispatch(TreeEvents::REORDER_NODE, $event);

        return;
    }
830911
public function replaceChild($childId, AbstractNode $newChild)
    {
        $oldChild                        = $this->getChild($childId);
        $keys                            = array_keys($this->children);
        $index                           = array_search($childId, $keys, true);
        $keys[$index]                    = $newChild->id();
        $this->children                  = array_combine($keys, $this->children);
        $this->children[$newChild->id()] = $newChild;
        unset($oldChild);
    }
993895
public function initializeNode($parentId, $language, $siteId, $order = 0)
    {
        /** @var NodeInterface $node */
        $node = new $this->nodeClass();
        $node->setSiteId($siteId);
        $node->setLanguage($language);
        $node->setMaxAge(NodeInterface::MAX_AGE);
        $node->setParentId($parentId);
        $node->setOrder($order);
        $node->setVersion($this->uniqueIdGenerator->generateUniqueId());
        $node->setCreatedBy($this->tokenStorage->getToken()->getUser()->getUsername());

        $parentNode = $this->nodeRepository->findInLastVersion($parentId, $language, $siteId);
        $status = $this->statusRepository->findOneByInitial();
        $node->setStatus($status);
        $nodeType = NodeInterface::TYPE_DEFAULT;
        if ($parentNode instanceof NodeInterface) {
            $nodeType = $parentNode->getNodeType();
            $node->setPath($parentNode->getPath());
        } else {
            $node->setNodeId(NodeInterface::ROOT_NODE_ID);
        }
        $node->setNodeType($nodeType);

        return $node;
    }
584277
public function setParentNode(ElementtypeStructureNode $parentNode = null)
    {
        if ($parentNode) {
            $this->parentDsId = $parentNode->getDsId();
        }

        $this->parentNode = $parentNode;

        return $this;
    }
291640
protected function detachFromTree(AbstractNestedNode $node)
    {
        if (true === $node->isRoot()) {
            return $this;
        }

        $this->refreshExistingNode($node)
                ->createQueryBuilder('n')
                ->set('n._leftnode', 'n._leftnode - :delta_node')
                ->set('n._rightnode', 'n._rightnode - :delta_node')
                ->set('n._level', 'n._level - :delta_level')
                ->set('n._root', ':node')
                ->andIsDescendantOf($node)
                ->setParameter('delta_node', $node->getLeftnode() - 1)
                ->setParameter('delta_level', $node->getLevel())
                ->setParameter('node', $node)
                ->update()
                ->getQuery()
                ->execute();

        $this->shiftRlValues($node, $node->getLeftnode(), - $node->getWeight());

        $node->setRightnode($node->getWeight())
                ->setLeftnode(1)
                ->setLevel(0)
                ->setRoot($node);

        return $this;
    }
519276
public function append(Node $node)
    {

        if (!is_array($this->_children)) {
            $this->_children = [];
        }

        $this->_children[] = $node;
        return $this;
    }
953339
public function setParent(AbstractParentNode $parent)
    {
        if (null !== $this->parent) {
            throw new \InvalidArgumentException('Node already got a parent!');
        }

        $this->parent = $parent;
    }
647926
function move( $newParentNodeID, $nodeID = 0 )
    {
        if ( $nodeID == 0 )
        {
            $node = $this;
            $nodeID = $node->attribute( 'node_id' );
        }
        else
        {
            $node = eZContentObjectTreeNode::fetch( $nodeID );
        }

        $oldPath = $node->attribute( 'path_string' );
        $oldParentNodeID = $node->attribute( 'parent_node_id' );
        $newParentNodeID =(int) $newParentNodeID;
        if ( $oldParentNodeID != $newParentNodeID )
        {
            $node->updateAndStoreModified();
            // Who moves which content should be logged.
            $object = $node->object();
            eZAudit::writeAudit( 'content-move', array( 'Node ID' => $node->attribute( 'node_id' ),
                                                        'Old parent node ID' => $oldParentNodeID, 'New parent node ID' => $newParentNodeID,
                                                        'Object ID' => $object->attribute( 'id' ), 'Content Name' => $object->attribute( 'name' ),
                                                        'Comment' => 'Moved the node to the given node: eZContentObjectTreeNode::move()' ) );

            $newParentNode = eZContentObjectTreeNode::fetch( $newParentNodeID );
            $newParentPath = $newParentNode->attribute( 'path_string' );
            $newParentDepth = $newParentNode->attribute( 'depth' );
            $newPath = $newParentPath . $nodeID;
            $oldDepth = $node->attribute( 'depth' );

            $oldPathLength = strlen( $oldPath );
            $moveQuery = "UPDATE
                                 ezcontentobject_tree
                          SET
                                 parent_node_id = $newParentNodeID
                          WHERE
                                 node_id = $nodeID";
            $db = eZDB::instance();
            $subStringString = $db->subString( 'path_string', $oldPathLength );
            $newPathString   = $db->concatString( array( "'$newPath'", $subStringString ) );
            $moveQuery1 = "UPDATE
                                 ezcontentobject_tree
                           SET
                                 path_identification_string = " .
                                 $db->concatString(
                                     array(
                                         "'" . $db->escapeString( $newParentNode->PathIdentificationString ) . "'",
                                         $db->subString(
                                             "path_identification_string",
                                             mb_strlen( $node->PathIdentificationString ) + 1
                                         )
                                     )
                                 ) . ",
                                 path_string = $newPathString,
                                 depth = depth + $newParentDepth - $oldDepth + 1
                           WHERE
                                 path_string LIKE '$oldPath%'";
            $db->begin();
            $db->query( $moveQuery );
            $db->query( $moveQuery1 );

            /// role system clean up
            // Clean up policies and limitations

            $expireRoleCache = false;

            $limitationsToFix = eZPolicyLimitation::findByType( 'SubTree', $node->attribute( 'path_string' ), false );
            if ( count( $limitationsToFix ) > 0 )
            {
                $limitationIDString = $db->generateSQLINStatement( $limitationsToFix, 'limitation_id' );
                $subStringString =  $db->subString( 'value', $oldPathLength );
                $newValue = $db->concatString( array( "'$newPath'", $subStringString ) );

                $query = "UPDATE
                                ezpolicy_limitation_value
                          SET
                                value = $newValue
                          WHERE
                                value LIKE '$oldPath%' AND $limitationIDString";

                $db->query( $query );

                $expireRoleCache = true;
            }

            // clean up limitations on role assignment level
            $countRows = $db->arrayQuery( "SELECT COUNT(*) AS row_count FROM ezuser_role WHERE limit_identifier='Subtree' AND limit_value LIKE '$oldPath%'" );
            $assignmentsToFixCount = $countRows[0]['row_count'];

            if ( $assignmentsToFixCount > 0 )
            {
                $subStringString =  $db->subString( 'limit_value', $oldPathLength );
                $newValue = $db->concatString( array( "'$newPath'", $subStringString ) );

                $db->query( "UPDATE
                                ezuser_role
                             SET
                                limit_value = $newValue
                             WHERE
                                limit_identifier='Subtree' AND limit_value LIKE '$oldPath%'"
                          );

               $expireRoleCache = true;
           }

            if ( $expireRoleCache )
            {
                eZRole::expireCache();
            }

            // Update "is_invisible" node attribute.
            $newNode = eZContentObjectTreeNode::fetch( $nodeID );
            eZContentObjectTreeNode::updateNodeVisibility( $newNode, $newParentNode );
            $db->commit();
        }
    }
638408
public function insertAsParentOf(NodeWrapper $node)
    {
        if($node == $this)
        {
            throw new \InvalidArgumentException('Cannot insert node as a parent of itself');
        }

        if($this->isValidNode())
        {
            throw new \InvalidArgumentException('Cannot insert a node that already has a place within the tree');
        }

        if($node->isRoot())
        {
            throw new \InvalidArgumentException('Cannot insert as parent of root');
        }

        $em = $this->getManager()->getEntityManager();
        $lftField = $this->getLeftFieldName();
        $rgtField = $this->getRightFieldName();

        $newLft = $node->getLeftValue();
        $newRgt = $node->getRightValue() + 2;
        $newRoot = $this->hasManyRoots() ? $node->getRootValue() : null;

        // beginTransaction
        $em->getConnection()->beginTransaction();
        try
        {
            // Make space for new node
            $this->shiftRLRange($newRgt - 1, 0, 2, $newRoot);

            // Slide child nodes over one and down one to allow new parent to wrap them
            $qb = $em->createQueryBuilder()
                ->update(get_class($this->getNode()), 'n')
                ->set("n.$lftField", "n.$lftField + 1")
                ->set("n.$rgtField", "n.$rgtField + 1")
                ->where("n.$lftField >= ?1")
                ->setParameter(1, $newLft)
                ->andWhere("n.$rgtField <= ?2")
                ->setParameter(2, $newRgt);
            if($this->hasManyRoots())
            {
                $qb->andWhere("n.".$this->getRootFieldName()." = ?3")
                    ->setParameter(3, $newRoot);
            }
            $qb->getQuery()->execute();
            $this->getManager()->updateValues($newLft, $newRgt, 1, $newRoot);

            $this->insertNode($newLft, $newRgt, $newRoot);

            $em->flush();
            $em->getConnection()->commit();
        }
        catch (\Exception $e)
        {
            // @codeCoverageIgnoreStart
            $em->close();
            $em->getConnection()->rollback();
            throw $e;
            // @codeCoverageIgnoreEnd
        }
        // endTransaction
    }