public static function move_category(category_controller $category, int $beforeid = 0) {
        global $DB;
        $records = $DB->get_records(category::TABLE, [
            'component' => $category->get('component'),
            'area' => $category->get('area'),
            'itemid' => $category->get('itemid')
        ], 'sortorder, id', '*');

        $id = $category->get('id');
        $categoriesids = array_values(array_diff(array_keys($records), [$id]));
        $idx = $beforeid ? array_search($beforeid, $categoriesids) : false;
        if ($idx === false) {
            // Set as the last category.
            $categoriesids = array_merge($categoriesids, [$id]);
        } else {
            // Set before category with id $beforeid.
            $categoriesids = array_merge(array_slice($categoriesids, 0, $idx), [$id], array_slice($categoriesids, $idx));
        }

        foreach (array_values($categoriesids) as $idx => $categoryid) {
            // Use persistent class to update the sortorder for each category that needs updating.
            if ($records[$categoryid]->sortorder != $idx) {
                $c = ($categoryid == $id) ? $category : category_controller::create(0, $records[$categoryid]);
                $c->set('sortorder', $idx);
                $c->save();
            }
        }
    }