Move element.

@param $id
@param int|mixed|string $position

@throws Exception

@return static

@example: move('user_id', 4);
@example: move('user_id', 'before:name");
@example: move('user_id', 'after:id");
199212
public function move(string $id, $position): self
    {
        if (is_numeric($position)) {
            return $this->toPosition($id, $position);
        }

        if (starts_with($position, 'before:')) {
            return $this->moveBefore($id, substr($position, 7));
        }

        if (starts_with($position, 'after:')) {
            return $this->moveAfter($id, substr($position, 6));
        }

        throw new Exception("Unknown moving direction: {$position}");
    }
1216997
public static function add( $element, $location = [] ) {
		if ( ! isset( self::$_elements[ $element ] ) ) {
			self::$_elements[ $element ] = [];
		}

		if ( empty( $location ) ) {
			$default_location = self::get_default_location( $element );

			if ( $default_location ) {
				self::$_elements[ $element ][] = [ $default_location ];
			} else {
				throw new \Exception( 'Element ' . $element . ' does not have a default location. You must supply the $location parameter.' );
			}
		} else {
			self::$_elements[ $element ][] = [ $location ];
		}

		add_action( 'init', [ __CLASS__, 'register_elements' ] );
	}
296486
protected function move($resource, $movement)
    {
        $resource->setPosition($resource->getPosition() + $movement);

        // TODO use ResourceManager
        $event = $this->getOperator()->update($resource);
        $event->toFlashes($this->getFlashBag());
    }
1041235
public function movePageDisplayOrderToSibling(Page $c, $position = 'before')
    {
        $myCID = $this->getCollectionPointerOriginalID() ?: $this->getCollectionID();
        $relatedCID = $c->getCollectionPointerOriginalID() ?: $c->getCollectionID();
        $pageIDs = [];
        $db = Database::connection();
        $r = $db->executeQuery('select cID from Pages where cParentID = ? and cID <> ? order by cDisplayOrder asc', [$this->getCollectionParentID(), $myCID]);
        while (($cID = $r->fetchColumn()) !== false) {
            if ($cID == $relatedCID && $position == 'before') {
                $pageIDs[] = $myCID;
            }
            $pageIDs[] = $cID;
            if ($cID == $relatedCID && $position == 'after') {
                $pageIDs[] = $myCID;
            }
        }
        $displayOrder = 0;
        foreach ($pageIDs as $cID) {
            $co = self::getByID($cID);
            $co->updateDisplayOrder($displayOrder);
            ++$displayOrder;
        }
    }
1299742
public function seek($position)
    {
        $position = (int) $position;
        if ($position < 0 || $position >= $this->_count) {
            // require_once 'Zend/Db/Table/Rowset/Exception.php';
            throw new Zend_Db_Table_Rowset_Exception("Illegal index $position");
        }
        $this->_pointer = $position;
        return $this;
    }
551692
public function relativeMove($model, $position)
    {
        $conditionAttributes = (array)$this->conditionAttributes;
        $owner = $this->owner;

        if (!empty($conditionAttributes)) {
            $sameCondition = true;
            foreach ($conditionAttributes as $attr) {
                if ($owner->getAttribute($attr) != $model->getAttribute($attr)) {
                    $sameCondition = false;
                    break;
                }
            }
            if (!$sameCondition) {
                // move in other condition category
                $this->moveToTop();
                // update condition attribute
                $condition = [];
                foreach ($conditionAttributes as $attr) {
                    $condition[$attr] = $model->getAttribute($attr);
                }
                $condition[$this->sortAttribute] = $owner->find()->andWhere($this->getCondition())->count() - 1;
                $owner->updateAttributes($condition);
            }
        }
        // calculate pos change
        $currentPos = $owner->getAttribute($this->sortAttribute);
        $destinationPos = $model->getAttribute($this->sortAttribute);
        if ($position == 'after') {
            $newPos = $destinationPos > $currentPos ? $destinationPos - 1 : $destinationPos;
        } else {
            $newPos = $destinationPos > $currentPos ? $destinationPos : $destinationPos + 1;
        }
        $this->moveToPosition($newPos);
    }
256602
public function reposition($position)
    {
        return Basecamp::todos($this->bucket->id)
                       ->reposition($this->id, $position);
    }
510442
protected function move_tour($id) {
        require_sesskey();

        $direction = required_param('direction', PARAM_INT);

        $tour = tour::instance($id);
        self::_move_tour($tour, $direction);

        redirect(helper::get_list_tour_link());
    }
107089
public function moveUpdateToTop($id)
    {
        return $this->send($this->getHttp()->post($this->url.'updates/'.$id.'/move_to_top.json'));
    }
1358620
public function add($id, $location = '#')
    {
        if ($location === '<' && count($keys = array_keys($this->items)) > 0) {
            return $this->addBefore($id, $keys[0]);
        } elseif (preg_match('/^(<|>|\^):(.+)$/', $location, $matches) && count($matches) >= 3) {
            return $this->pickTraverseFromMatchedExpression($id, $matches[1], $matches[2]);
        }
        return $this->addParent($id);
    }
631851
public function setEndPositionId($id, $relatedId) {
		// find
		$model = $this->get($id);

		if ($model === null) {
			return new NotFound(['message' => 'Skill not found.']);
		}

		// update
		if ($this->doSetEndPositionId($model, $relatedId)) {
			$this->dispatch(SkillEvent::PRE_END_POSITION_UPDATE, $model);
			$this->dispatch(SkillEvent::PRE_SAVE, $model);
			$model->save();
			$this->dispatch(SkillEvent::POST_END_POSITION_UPDATE, $model);
			$this->dispatch(SkillEvent::POST_SAVE, $model);

			return Updated(['model' => $model]);
		}

		return NotUpdated(['model' => $model]);
	}
187841
public function insert($element, $position, Closure $callback = null): self
    {
        $element = $this->createElement($element);

        if ($callback) {
            $callback($element);
        }

        if (is_string($position)) {
            $this->push($element);

            return $this->move($element->id(), $position);
        }

        if ($position >= $this->count()) {
            return $this->push($element);
        }

        if (0 === $position) {
            return $this->prepend($element);
        }

        $items = [];
        foreach ($this->all() as $index => $value) {
            if ($index === $position) {
                array_push($items, $element);
            }

            array_push($items, $value);
        }
        $this->items = $items;

        return $this;
    }
1138216
public function moveNode(string $id, string $action = '')
    {
        $this->request->allowMethod('post');

        if (!in_array($action, ['up', 'down'])) {
            $this->Flash->error((string)__('Unknown move action "{0}".', $action));

            return $this->redirect($this->referer());
        }

        $entity = $this->DblistItems->get($id);

        if ($this->DblistItems->{'move' . $action}($entity)) {
            $this->Flash->success((string)__('{0} has been moved {1} successfully.', $entity->get('name'), $action));
        } else {
            $this->Flash->error((string)__('Fail to move {0} {1}.', $entity->get('name'), $action));
        }

        return $this->redirect($this->referer());
    }
1058360
public function setPosition($position = self::POSITION_RIGHT) {
		if (!in_array($position,self::$_positionXLref)) {
			return false;
		}

		$this->_position = $position;
		return true;
	}
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;
    }
1119392
public function setPosition($position)
    {
        if (false === Numeric::isPositiveInteger($position, false)) {
            throw new InvalidArgumentException('A position must be a positive integer.');
        }
        $this->_position = $position;
        return $this;
    }
266907
public function batchExecute(array $requests, Position $position, $attempt = 0)
    {
        $this->lastRequestMs = round(microtime(true) * 1000);

        $envelope = $this->createEnvelope($requests, $position);
        $contents = $envelope->toStream()->getContents();

        try {
            $response = $this->httpClient->post($this->endpoint, [
                'body' => $contents
            ]);
        } catch(\Exception $e) {
            throw new RequestException($e->getMessage(), $e->getCode(), $e);
        }

        $this->logger->debug("Received HTTP Status {StatusCode}", array('StatusCode' => $response->getStatusCode()));

        if ($response->getStatusCode() !== 200) {
            throw new \Exception("Wrong statuscode: " . $response->getStatusCode());
        }

        if (!$response->getBody()->isReadable()) {
            throw new NoResponse("Unreadable stream.");
        }

        if ($response->getBody()->getSize() < 1) {
            throw new NoResponse("Empty body.");
        }

        $responseEnvelope = new ResponseEnvelope($response->getBody()->getContents());
        $this->lastResponse = $responseEnvelope;

        if ($responseEnvelope->getAuthTicket()) {
            $this->logger->debug("Received AuthTicket");
            $this->ticket = AuthTicket::fromProto($responseEnvelope->getAuthTicket());
        }

        if (!empty($responseEnvelope->getApiUrl())) {
            $this->logger->debug("Received new API Endpoint {URL}", array('URL' => $responseEnvelope->getApiUrl()));
            $this->setEndpoint($responseEnvelope->getApiUrl());
        }

        $this->logger->debug(
            "Received ResponseEnvelope with StatusCode {StatusCode}",
            array(
                'StatusCode' => $responseEnvelope->getStatusCode()->name()
            )
        );

        if (
            $responseEnvelope->getStatusCode() === ResponseEnvelope\StatusCode::REDIRECT()
        ) {
            return $this->batchExecute($requests, $position);
        }

        if ($responseEnvelope->getStatusCode() === ResponseEnvelope\StatusCode::SESSION_INVALIDATED()) {
            $attempt++;
            if ($attempt >= $this->retryCount) {
                throw new ThrottledException();
            }
            sleep(1);
            return $this->batchExecute($requests, $position, $attempt);
        }

        if ($responseEnvelope->getStatusCode() === ResponseEnvelope\StatusCode::INVALID_PLATFORM_REQUEST()) {
            $attempt++;
            if ($attempt >= $this->retryCount) {
                throw new ThrottledException();
            }
            sleep(1);
            return $this->batchExecute($requests, $position, $attempt);
        }

        if ($responseEnvelope->getStatusCode() === ResponseEnvelope\StatusCode::INVALID_AUTH_TOKEN()) {
            $this->token = null;
            $this->ticket = null;
            return $this->batchExecute($requests, $position);
        }

        if (!empty($responseEnvelope->getReturnsList())) {
            $this->retryCount = 0;
            return $responseEnvelope->getReturnsList();
        }

        throw new NoResponse("No return messages in response.");
    }