Skip to content

Commit

Permalink
category-create reuse fix #439
Browse files Browse the repository at this point in the history
  • Loading branch information
mi7chal committed Aug 28, 2024
1 parent 9c93d3f commit 3787c24
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions Moosh/Command/Moodle39/Category/CategoryCreate.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,25 @@ public function execute()
$category->parent = $options['parent'];
$category->idnumber = $options['idnumber'];
$category->visible = $options['visible'];

if($this->verbose) {
$name = $category->name;
mtrace("Creating category $name");
}

if ($options['reuse'] && $existing = $this->find_category($category)) {
$newcategory = $existing;

$name = $newcategory->name;
$id = $newcategory->id;
print "Category $name with id: $id exists. Skipping, because --reuse param is present.\n";
} else {
$newcategory = $this->create_category($category);
}

//either use API create_course
echo $newcategory->id . "\n";
$name = $newcategory->name;
$id = $newcategory->id;
print "Created category $name with id: $id.\n";
}
}
}

Expand All @@ -58,13 +69,25 @@ protected function find_category($category)
{
global $DB;
$params = array('name' => $category->name);
foreach (array('idnumber', 'parent', 'description') as $param) {
if ($category->$param) {
$select = "name = :name";
foreach (array('idnumber', 'parent') as $param) {
if ($category->$param !== "") {
$params[$param] = $category->$param;
$select .= " AND $param = :$param";
}
}
$categories = $DB->get_records('course_categories', $params);
if (count($categories) == 1) {

// description is of text type, so requires sql_compare_text to be found and do not throw
if($category->description !== "") {
$params["description"] = $category->description;
$select .= "AND " . $DB->sql_compare_text('description') . " = :description";
}


$categories = $DB->get_records_select('course_categories', $select, $params);

// sometimes more than one category might exist
if (count($categories) >= 1) {
return array_pop($categories);
} else {
return null;
Expand Down

0 comments on commit 3787c24

Please sign in to comment.