Appends a sibling within the current depth.

@param EntityInterface $sibling
@param int|null $position
@param bool $returnSibling
@return EntityInterface
18260
public function addSibling(EntityInterface $sibling, $position = null, $returnSibling = false)
    {
        if ($this->exists) {
            if (is_null($position)) {
                $position = $this->getNextAfterLastPosition();
            }

            $sibling->moveTo($position, $this->parent_id);
        }

        return ($returnSibling === true ? $sibling : $this);
    }
1082288
public function callWith($method, $args, $object, $returnRelation = false)
    {
        if (is_string($object)) {
            $object = Reflect::create($object);
        }

        /**
         * Check if $method prefix is listed in autocallPrefixes.
         */
        foreach ($this->autocallPrefixes as $prefix) {
            if (substr($method, 0, strlen($prefix)) === $prefix
                && strtoupper(substr($method, strlen($prefix), 1)) == substr($method, strlen($prefix), 1)
            ) {
                /**
                 * We are calling relation function without arguments: $entity->something();.
                 */
                $relationMethod = lcfirst(substr($method, strlen($prefix)));
                $relation = Reflect::method($object, $relationMethod, $args);
                // $relation = $object->{$relationMethod}();

                if (isset($args[0]) && ($args[0] instanceof Closure || is_only_callable($args[0]))) {
                    /**
                     * If callback was added, we run it.
                     * Now, this is a problem if we're making join because query was already merged.
                     * So, we'll call this magically and provide both - relation and query.
                     *
                     * @T00D00
                     */
                    if (in_array($prefix, ['join', 'leftJoin', 'innerJoin'])) {
                        $rightEntity = $relation->getRightEntity();
                        $oldEntityQuery = $rightEntity->getQuery();
                        $rightEntity->setQuery($relation->getQuery());
                        Reflect::call($args[0], [$relation, $relation->getQuery()]);
                        $rightEntity->setQuery($oldEntityQuery);
                    } else {
                        Reflect::call($args[0], [$relation, $relation->getQuery()]);
                    }
                }

                if ($prefix == 'leftJoin') {
                    $relation->leftJoin();
                }
                /**
                 * We'll call $entity->with($relation), $entity->join($relation) or $entity->required($relation), and return Relation;
                 */
                $return = $object->{$prefix == 'leftJoin' ? 'join' : $prefix}($relation);

                /**
                 * Then we return relation.
                 */
                return $returnRelation
                    ? $relation
                    : $return;
            }
        }

        if (!method_exists($object, $method)) {
            throw new Exception('Method ' . $method . ' does not exist in ' . get_class($object));
        }

        /**
         * Autoprefixes failed, return relation, probably?
         */
        $relation = Reflect::method($object, $method, $args);

        if (isset($args[0]) && ($args[0] instanceof Closure || is_only_callable($args[0]))) {
            Reflect::call($args[0], [$relation, $relation->getQuery()]);
        }

        return $relation;
    }
102895
public Returner currentPosition(@IntRange(from = 0, to = Integer.MAX_VALUE) int currentPosition) {
        this.mCurrentPosition = currentPosition;
        return (Returner) this;
    }
1361826
public function insertElement( $preposition, $refElement, Element $element, $void,
		$sourceStart, $sourceLength
	) {
		list( $parent, $refNode ) = $this->interpretPlacement( $preposition, $refElement );
		$children =& $parent->children;
		$lastChildIndex = count( $children ) - 1;
		$lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;

		if ( $element->userData ) {
			// This element has already been inserted, this is a reparenting operation
			$self = $element->userData;
			$oldParent = $this->nodes[$self->parentId];
			$oldChildren =& $oldParent->children;
			$oldChildIndex = array_search( $self, $oldChildren, true );
			if ( $oldChildIndex === false ) {
				throw new SerializerError( "cannot find node to reparent: " .
					$element->getDebugTag() );
			}
			// Remove from the old parent, update parent pointer
			$oldChildren[$oldChildIndex] = '';
			$self->parentId = $parent->id;
		} else {
			// Inserting an element which has not been seen before
			$id = $element->uid;
			$self = new SerializerNode( $id, $parent->id, $element->namespace,
				$element->name, $element->attrs, $void );
			$this->nodes[$id] = $element->userData = $self;
		}

		if ( $preposition === TreeBuilder::BEFORE ) {
			// Insert before element
			if ( $lastChild !== $refNode ) {
				$refIndex = array_search( $refNode, $children, true );
				throw new SerializerError( "invalid insert position $refIndex/$lastChildIndex" );
			}
			$children[$lastChildIndex] = $self;
			$children[$lastChildIndex + 1] = $refNode;
		} else {
			// Append to the list of children
			$children[] = $self;
		}
	}
68318
public function moveToParent($movedNode, $newParent, $position=null)
    {

        $this->callBeforeListeners('move', [$movedNode, $newParent, $position]);

        $this->model()->placeAt($movedNode, $newParent, $position);

        if (!$position) {
            $this->model()->makeChildOf($movedNode, $newParent);
        } else {
            $this->model()->placeAt($movedNode, $newParent, $position);
        }

        $this->callAfterListeners('move', [$movedNode, $newParent, $position]);

        return $this;
    }
146483
public function addInteraction(Interaction $interaction, $body){
        $returnValue = false;

        if(!is_null($interaction)){
            $returnValue = $this->getBody()->setElement($interaction, $body);
        }

        return (bool) $returnValue;
    }
1371512
def add_sibling(self, pos=None, **kwargs):
        """"""

        pos = self._prepare_pos_var_for_add_sibling(pos)

        if len(kwargs) == 1 and 'instance' in kwargs:
            # adding the passed (unsaved) instance to the tree
            newobj = kwargs['instance']
            if newobj.pk:
                raise NodeAlreadySaved("Attempted to add a tree node that is "\
                    "already in the database")
        else:
            # creating a new object
            newobj = get_result_class(self.__class__)(**kwargs)

        newobj.depth = self.depth

        sql = None
        target = self

        if target.is_root():
            newobj.lft = 1
            newobj.rgt = 2
            if pos == 'sorted-sibling':
                siblings = list(target.get_sorted_pos_queryset(
                    target.get_siblings(), newobj))
                if siblings:
                    pos = 'left'
                    target = siblings[0]
                else:
                    pos = 'last-sibling'

            last_root = target.__class__.get_last_root_node()
            if (
                    (pos == 'last-sibling') or
                    (pos == 'right' and target == last_root)
            ):
                newobj.tree_id = last_root.tree_id + 1
            else:
                newpos = {'first-sibling': 1,
                          'left': target.tree_id,
                          'right': target.tree_id + 1}[pos]
                sql, params = target.__class__._move_tree_right(newpos)

                newobj.tree_id = newpos
        else:
            newobj.tree_id = target.tree_id

            if pos == 'sorted-sibling':
                siblings = list(target.get_sorted_pos_queryset(
                    target.get_siblings(), newobj))
                if siblings:
                    pos = 'left'
                    target = siblings[0]
                else:
                    pos = 'last-sibling'

            if pos in ('left', 'right', 'first-sibling'):
                siblings = list(target.get_siblings())

                if pos == 'right':
                    if target == siblings[-1]:
                        pos = 'last-sibling'
                    else:
                        pos = 'left'
                        found = False
                        for node in siblings:
                            if found:
                                target = node
                                break
                            elif node == target:
                                found = True
                if pos == 'left':
                    if target == siblings[0]:
                        pos = 'first-sibling'
                if pos == 'first-sibling':
                    target = siblings[0]

            move_right = self.__class__._move_right

            if pos == 'last-sibling':
                newpos = target.get_parent().rgt
                sql, params = move_right(target.tree_id, newpos, False, 2)
            elif pos == 'first-sibling':
                newpos = target.lft
                sql, params = move_right(target.tree_id, newpos - 1, False, 2)
            elif pos == 'left':
                newpos = target.lft
                sql, params = move_right(target.tree_id, newpos, True, 2)

            newobj.lft = newpos
            newobj.rgt = newpos + 1

        # saving the instance before returning it
        if sql:
            cursor = self._get_database_cursor('write')
            cursor.execute(sql, params)
        newobj.save()


        return newobj
1365900
def append_sibling_object(self, linenum, indent, path):
        
        frame = self.current_frame()
        assert frame.indent is not None and frame.indent == indent
        self.pop_frame()
        self.append_child_object(linenum, indent, path)
746791
public function newPlacementAction(Request $request, $newMenuItemId, $menuItemId)
    {
        $sibling = $request->get('sibling');

        /** @var MenuItemManager $menuItemManager */
        $menuItemManager = $this->get('networking_init_cms.menu_item_manager');
        $newMenuItem = $menuItemManager->find($newMenuItemId);
        $menuItem = $menuItemManager->find($menuItemId);

        if (!$newMenuItem || !$menuItem) {
            throw new NotFoundHttpException();
        }

        $data = [];
        try {
            if ($sibling) {
                $menuItemManager->persistAsNextSiblingOf($newMenuItem, $menuItem);
            } else {
                $menuItemManager->persistAsFirstChildOf($newMenuItem, $menuItem);
            }
            $this->getDoctrine()->getManager()->flush();
            $data = [
                'result' => 'ok',
                'objectId' => $this->admin->getNormalizedIdentifier($newMenuItem),
            ];

            return $this->renderJson($data);
        } catch (\Exception $e) {
            return $this->renderJson($data);
        }
    }
348715
protected function reorder($oldPosition = null, $position = null, $siblings = [])
    {
        if (null === $oldPosition || null === $position || true === empty($siblings)) {
            return ['error' => Yii::t('jstw', 'Invalid data provided!')];
        }
        $nodeId = $siblings[$position];
        $class = $this->className;
        if ($oldPosition > $position) {
            //change next
            $nodeOperator = '-';
            $siblingsOperator = '+';
            $workWith = array_slice($siblings, $position, $oldPosition - $position + 1);
        } else if ($oldPosition < $position) {
            //change previous
            $nodeOperator = '+';
            $siblingsOperator = '-';
            $workWith = array_slice($siblings, $oldPosition, $position - $oldPosition + 1);
        } else {
            return true;
        }
        if (true === empty($workWith)) {
            return ['error' => Yii::t('jstw', 'Invalid data provided!')];
        }
        $lr = $workWithLr = $this->getLr($workWith);
        if (true === empty($lr)) {
            return ['error' => Yii::t('jstw', 'Invalid data provided!')];
        }
        unset($workWithLr[$nodeId]);
        $lft = array_column($workWithLr, $this->leftAttribute);
        $lft = min($lft);
        $rgt = array_column($workWithLr, $this->rightAttribute);
        $rgt = max($rgt);
        $nodeCondition = [
            'and',
            ['>=', $this->leftAttribute, $lft],
            ['<=', $this->rightAttribute, $rgt]
        ];
        $this->applyRootCondition($nodeCondition);
        $nodeDelta = $this->getCount($nodeCondition);
        $nodeDelta *= 2;
        $siblingsCondition = [
            'and',
            ['>=', $this->leftAttribute, $lr[$nodeId][$this->leftAttribute]],
            ['<=', $this->rightAttribute, $lr[$nodeId][$this->rightAttribute]]
        ];
        $this->applyRootCondition($siblingsCondition);
        $nodeChildren = $this->getChildIds($siblingsCondition);
        $siblingsDelta = count($nodeChildren) * 2;
        $db = Yii::$app->getDb();
        $transaction = $db->beginTransaction();
        try {
            //updating necessary node siblings
            $db->createCommand()->update(
                $class::tableName(),
                [
                    $this->leftAttribute => new Expression($this->leftAttribute . sprintf('%s%d', $siblingsOperator, $siblingsDelta)),
                    $this->rightAttribute => new Expression($this->rightAttribute . sprintf('%s%d', $siblingsOperator, $siblingsDelta)),
                ],
                $nodeCondition
            )->execute();
            //updating node
            $db->createCommand()->update(
                $class::tableName(),
                [
                    $this->leftAttribute => new Expression($this->leftAttribute . sprintf('%s%d', $nodeOperator, $nodeDelta)),
                    $this->rightAttribute => new Expression($this->rightAttribute . sprintf('%s%d', $nodeOperator, $nodeDelta)),
                ],
                ['id' => $nodeChildren]
            )->execute();
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['error' => $e->getMessage()];
        }
        return true;
    }
1083788
public function addSiblings(array $siblings, $from = null)
    {
        if ($this->exists) {
            if (is_null($from)) {
                $from = $this->getNextAfterLastPosition();
            }

            $parent = $this->getParent();
            /**
             * @var Entity $sibling
             */
            foreach ($siblings as $sibling) {
                $sibling->moveTo($from, $parent);
                $from++;
            }
        }

        return $this;
    }
760884
private function findSibling(Collection $elements, SortableInterface $current, $next = false)
    {
        if ($next) {
            $sibling = $elements->filter(function (SortableInterface $s) use ($current) {
                return $s->getPosition() > $current->getPosition();
            })->first();
        } else {
            $sibling = $elements->filter(function (SortableInterface $s) use ($current) {
                return $s->getPosition() < $current->getPosition();
            })->last();
        }

        return $sibling ?: null;
    }
606267
public function addReturnreceipt(\Innova\CollecticielBundle\Entity\ReturnReceipt $returnreceipt)
    {
        $this->returnreceipts[] = $returnreceipt;

        return $this;
    }
614122
private function getNextTag(&$s, $i, &$position)
    {
        $j = mb_strpos($s, '[', $i);
        $k = mb_strpos($s, ']', $j + 1);

        if ($j === false || $k === false) {
            $position = false;
            return null;
        }

        $t = mb_substr($s, $j + 1, $k - ($j + 1));
        $l = mb_strrpos($t, '[');

        if ($l !== false) {
            $j += $l + 1;
        }

        $position = $j;

        $tagString = mb_substr($s, $j, $k - $j + 1);

        return new Tag($tagString, $this->getHandlers());
    }
777195
public function addModifier(ModifierInterface $modifier, $position = null, $continueOnException = false)
    {
        if (null === $position) {
            $position = sizeof($this->modifiers) ? (max(array_keys($this->modifiers)) + 1) : 0;
        }

        if (!is_numeric($position)) {
            throw new \InvalidArgumentException('Position must be a number');
        }

        if (array_key_exists($position, $this->modifiers)) {
            throw new \InvalidArgumentException(sprintf('There already is a modifier at position %d', $position));
        }

        $this->modifiers[$position] = $modifier;
        $this->continues[$position] = $continueOnException;

        ksort($this->modifiers);
    }
1106203
protected function move($position = null, $siblings = [], $oldParentId)
    {
        $class = $this->className;
        if (null === $oldParent = $class::findOne($oldParentId)) {
            return ['error' => Yii::t('jstw', "Old parent with id '{id}' not found!", ['id' => $oldParentId])];
        }
        $nodeCountCondition = [
            'and',
            ['>=', $this->leftAttribute, $this->node{$this->leftAttribute}],
            ['<=', $this->rightAttribute, $this->node{$this->rightAttribute}]
        ];
        $this->applyRootCondition($nodeCountCondition);
        $nodeChildren = $this->getChildIds($nodeCountCondition);
        $siblingsDelta = count($nodeChildren) * 2;
        if ($position == 0) {
            $compareRight = $this->parent->{$this->leftAttribute} + 1;
        } else {
            if (false === isset($siblings[$position - 1])) {
                return ['error' => Yii::t('jstw', 'New previous sibling does not exist')];
            }
            $newPrevSiblingId = $siblings[$position - 1];
            $newPrevSiblingData = $this->getLr($newPrevSiblingId);
            $compareRight = $newPrevSiblingData[$newPrevSiblingId][$this->rightAttribute];
        }
        if ($this->node->{$this->leftAttribute} > $compareRight) {
            //move node up
            if ($position == 0) {
                $leftFrom = $compareRight;
            } else {
                $leftFrom = $compareRight + 1;
            }
            $rightTo = $this->node->{$this->leftAttribute};
            $nodeDelta = $this->node->{$this->leftAttribute} - $leftFrom;
            $nodeOperator = '-';
            $parentOperator = $siblingsOperator = '+';
            $newParentUpdateField = $this->rightAttribute;
            $oldParentUpdateField = $this->leftAttribute;
        } else if ($this->node->{$this->leftAttribute} < $compareRight) {
            //move node down
            $leftFrom = $this->node->{$this->rightAttribute};
            if ($position == 0) {
                $rightTo = $compareRight - 1;
            } else {
                $rightTo = $compareRight;
            }
            $nodeOperator = '+';
            $parentOperator = $siblingsOperator = '-';
            $nodeDelta = $rightTo - $siblingsDelta + 1 - $this->node->{$this->leftAttribute};
            $newParentUpdateField = $this->leftAttribute;
            $oldParentUpdateField = $this->rightAttribute;
        } else {
            return ['error' => Yii::t('jstw', 'There are two nodes with same "left" value. This should not be.')];
        }
        $siblingsCondition = [
            'and',
            ['>=', $this->leftAttribute, $leftFrom],
            ['<=', $this->rightAttribute, $rightTo]
        ];
        $this->applyRootCondition($siblingsCondition);
        $db = Yii::$app->getDb();
        $transaction = $db->beginTransaction();
        $oldParentDepth = $oldParent->{$this->depthAttribute};
        $newParentDepth = $this->parent->{$this->depthAttribute};
        if ($newParentDepth < $oldParentDepth) {
            $depthOperator = '-';
            $depthDelta = $oldParentDepth - $newParentDepth;
        } else {
            $depthOperator = '+';
            $depthDelta = $newParentDepth - $oldParentDepth;
        }
        $commonParentsCondition = [
            'and',
            ['<', $this->leftAttribute, $leftFrom],
            ['>', $this->rightAttribute, $rightTo]
        ];
        $this->applyRootCondition($commonParentsCondition);
        $commonParentsIds = $class::find()->select('id')->where($commonParentsCondition)->column();
        $commonCondition = [
            ['!=', $this->depthAttribute, 0],
            ['not in', 'id', $commonParentsIds],
        ];
        $this->applyRootCondition($commonCondition);
        $newParentCondition = array_merge([
            'and',
            ['<=', $this->leftAttribute, $this->parent->{$this->leftAttribute}],
            ['>=', $this->rightAttribute, $this->parent->{$this->rightAttribute}],
        ], $commonCondition);
        $oldParentsCondition = array_merge([
            'and',
            ['<', $this->leftAttribute, $this->node->{$this->leftAttribute}],
            ['>', $this->rightAttribute, $this->node->{$this->rightAttribute}],
        ], $commonCondition);
        try {
            //updating necessary node siblings
            $db->createCommand()->update(
                $class::tableName(),
                [
                    $this->leftAttribute => new Expression($this->leftAttribute . sprintf('%s%d', $siblingsOperator, $siblingsDelta)),
                    $this->rightAttribute => new Expression($this->rightAttribute . sprintf('%s%d', $siblingsOperator, $siblingsDelta)),
                ],
                $siblingsCondition
            )->execute();
            //updating old parents
            $db->createCommand()->update(
                $class::tableName(),
                [
                    //down - right
                    $oldParentUpdateField => new Expression($oldParentUpdateField . sprintf('%s%d', $parentOperator, $siblingsDelta)),
                ],
                $oldParentsCondition
            )->execute();
            //updating new parents
            $db->createCommand()->update(
                $class::tableName(),
                [
                    //down - left
                    $newParentUpdateField => new Expression($newParentUpdateField . sprintf('%s%d', $parentOperator, $siblingsDelta)),
                ],
                $newParentCondition
            )->execute();
            //updating node with children
            $db->createCommand()->update(
                $class::tableName(),
                [
                    $this->leftAttribute => new Expression($this->leftAttribute . sprintf('%s%d', $nodeOperator, $nodeDelta)),
                    $this->rightAttribute => new Expression($this->rightAttribute . sprintf('%s%d', $nodeOperator, $nodeDelta)),
                    $this->depthAttribute => new Expression($this->depthAttribute . sprintf('%s%d', $depthOperator, $depthDelta)),
                ],
                ['id' => $nodeChildren]
            )->execute();
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['error' => $e->getMessage()];
        }
        return true;
    }
484946
public function getCellByPosition(TablePosition $position)
    {
        $row = $this->getRow($position->getRow());

        return $row ? $row->getCell($position->getCell()) : null;
    }