Create categories

@param array $categories - see create_categories_parameters() for the array structure
@return array - see create_categories_returns() for the array structure
@since Moodle 2.3
178266
public static function create_categories($categories) {
        global $DB;

        $params = self::validate_parameters(self::create_categories_parameters(),
                        array('categories' => $categories));

        $transaction = $DB->start_delegated_transaction();

        $createdcategories = array();
        foreach ($params['categories'] as $category) {
            if ($category['parent']) {
                if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
                    throw new moodle_exception('unknowcategory');
                }
                $context = context_coursecat::instance($category['parent']);
            } else {
                $context = context_system::instance();
            }
            self::validate_context($context);
            require_capability('moodle/category:manage', $context);

            // this will validate format and throw an exception if there are errors
            external_validate_format($category['descriptionformat']);

            $newcategory = core_course_category::create($category);
            $context = context_coursecat::instance($newcategory->id);

            $createdcategories[] = array(
                'id' => $newcategory->id,
                'name' => external_format_string($newcategory->name, $context),
            );
        }

        $transaction->allow_commit();

        return $createdcategories;
    }
886692
public function addCategory(\Haven\CoreBundle\Entity\Category $categories)
    {
        $this->categories[] = $categories;
    
        return $this;
    }
501906
protected function buildProductCategories(array &$productData, array $categories)
    {
        /** @var array $categories */
        foreach ($categories as $category) {
            $productData['categories'][] = [
                'code' => (string) $this->arrayExtract($category, 'code', ''),
                'name' => (string) $this->arrayExtract($category, 'name', ''),
            ];
        }

        return $productData;
    }
1063361
public static function delete_categories($categories) {
        global $CFG, $DB;
        require_once($CFG->dirroot . "/course/lib.php");

        // Validate parameters.
        $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['categories'] as $category) {
            $deletecat = core_course_category::get($category['id'], MUST_EXIST);
            $context = context_coursecat::instance($deletecat->id);
            require_capability('moodle/category:manage', $context);
            self::validate_context($context);
            self::validate_context(get_category_or_system_context($deletecat->parent));

            if ($category['recursive']) {
                // If recursive was specified, then we recursively delete the category's contents.
                if ($deletecat->can_delete_full()) {
                    $deletecat->delete_full(false);
                } else {
                    throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
                }
            } else {
                // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
                // If the parent is the root, moving is not supported (because a course must always be inside a category).
                // We must move to an existing category.
                if (!empty($category['newparent'])) {
                    $newparentcat = core_course_category::get($category['newparent']);
                } else {
                    $newparentcat = core_course_category::get($deletecat->parent);
                }

                // This operation is not allowed. We must move contents to an existing category.
                if (!$newparentcat->id) {
                    throw new moodle_exception('movecatcontentstoroot');
                }

                self::validate_context(context_coursecat::instance($newparentcat->id));
                if ($deletecat->can_move_content_to($newparentcat->id)) {
                    $deletecat->delete_move($newparentcat->id, false);
                } else {
                    throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
                }
            }
        }

        $transaction->allow_commit();
    }
971918
public function addCategory($category)
	{
		if (!is_string($category))
		{
			// @codeCoverageIgnoreStart
			throw new \LogicException('Category must be of a type "string"');
			// @codeCoverageIgnoreEnd
		}
		$this->categories[$category] = $category;

		return $this;
	}
245799
public static function create_from_question_category_instance($category, $context = null) {

        $params = ['objectid' => $category->id];

        if (!empty($category->contextid)) {
            $params['contextid'] = $category->contextid;
        }

        $params['context'] = $context;

        $event = self::create($params);
        return $event;
    }
687910
protected function find_categories_after($category) {
        $return = array();
        $categoryarray = $this->categories;
        foreach ($categoryarray as $categoryelement) {
            if ($categoryelement->after == $category->name) {
                // Find all categories that comes after this category as well.
                $categoryelement->sort_nodes();
                $return = array_merge($return, array($categoryelement->name => $categoryelement),
                        $this->find_categories_after($categoryelement));
            }
        }
        return $return;
    }
1040670
public static function get_all_question_types_in_categories($categories) {
        global $DB;

        list($categorysql, $params) = $DB->get_in_or_equal($categories);
        $sql = "SELECT DISTINCT q.qtype
                FROM {question} q
                WHERE q.category $categorysql";

        $qtypes = $DB->get_fieldset_sql($sql, $params);
        return $qtypes;
    }
30393
protected function createNodes($nodes)
    {
        // $parent is the array of parent nodes.
        $parent = [];

        foreach ($nodes as $load_record) {
            $match = preg_match('/^\*+/', $load_record, $matches);

            // If there is no match then we have hit a top level category.
            // Add this to the $result array and reset the $parent array.
            if ($match === 0) {
                $node_name = trim($load_record);
                $root_node = Category::create([
                    'name'          => $node_name,
                    'description'   => $node_name,
                ]);

                $parent = [
                    0   => $root_node,
                ];
                continue;
            }

            // If there is a match then check how many levels deep we are.
            $levels = strlen($matches[0]);

            // Grab the node name
            $node_name = trim(substr($load_record, $levels));

            // Grab the current node at the level of the parent.
            /** @var Category $current */
            $current = $parent[$levels - 1];

            // Add this node as a child of the parent.
            $child_node = $current->children()->create([
                'name' => $node_name
            ]);

            // Update the description, just for fun
            $child_node->description = $child_node->path;
            $child_node->save();

            // Store this node name as a potential future parent.
            $parent[$levels] = $child_node;
        }
    }
1075295
public function batchRead(array $categories) {
        $requests = [];

        foreach ($categories as $category) {
            $requests[] = [
                'method' => 'cmdb.category_info',
                'params' => array(
                    'category' => $category
                )
            ];
        }

        return $this->api->batchRequest($requests);
    }
681276
public function setCategory(\Innova\LexiconBundle\Entity\Category $category = null)
    {
        $this->category = $category;

        return $this;
    }
1052642
private static function _get_children_recursion($category) {

        $children_array = array();
        foreach ($category->children as $sortorder=>$child) {

            if (array_key_exists('itemtype', $child)) {
                $grade_item = new grade_item($child, false);

                if (in_array($grade_item->itemtype, array('course', 'category'))) {
                    $type  = $grade_item->itemtype.'item';
                    $depth = $category->depth;

                } else {
                    $type  = 'item';
                    $depth = $category->depth; // we use this to set the same colour
                }
                $children_array[$sortorder] = array('object'=>$grade_item, 'type'=>$type, 'depth'=>$depth);

            } else {
                $children = grade_category::_get_children_recursion($child);
                $grade_category = new grade_category($child, false);

                if (empty($children)) {
                    $children = array();
                }
                $children_array[$sortorder] = array('object'=>$grade_category, 'type'=>'category', 'depth'=>$grade_category->depth, 'children'=>$children);
            }
        }

        // sort the array
        ksort($children_array);

        return $children_array;
    }
990983
public function category(Category $category)
    {
        $this->category = $category;

        $this->category->categorise($this);
    }
160841
public function inCategories(array $categories): self
    {
        foreach ($categories as $category) {
            if (is_array($category)) {
                $this->inCategory($category['category'], $category['domain']);
            } else {
                $this->inCategory($category);
            }
        }

        return $this;
    }
281038
public function getCategory($categories)
    {
        $this->validateNumericArray('categories', $categories);
        $stats = $this->getGlobal();
        $stats['categories'] = $categories;
        return $stats;
    }
407166
public function all(array $categories = array())
	{
		$handlers = array();

		foreach ($this->handlers as $handler)
		{
			$handlerCategories = $this->handlers->getInfo();
			if (array() === $categories || array() !== array_intersect($handlerCategories, $categories))
			{
				$handlers[] = $handler;
			}
		}

		return $handlers;
	}
900473
public static function createCategory($data)
	{
		JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_categories/models');
		JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_categories/tables');

		$categoryModel = JModelLegacy::getInstance('Category', 'CategoriesModel', array('ignore_request' => true));
		$categoryModel->save($data);

		$catid = $categoryModel->getState('category.id');

		return $catid;
	}