From 3787c248425fb35942153a4972dff9139f741858 Mon Sep 17 00:00:00 2001 From: Michal Chruscielski Date: Wed, 28 Aug 2024 15:54:28 +0200 Subject: [PATCH] category-create reuse fix #439 --- .../Moodle39/Category/CategoryCreate.php | 37 +++++++++++++++---- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/Moosh/Command/Moodle39/Category/CategoryCreate.php b/Moosh/Command/Moodle39/Category/CategoryCreate.php index 3a64bb68..806c96c2 100755 --- a/Moosh/Command/Moodle39/Category/CategoryCreate.php +++ b/Moosh/Command/Moodle39/Category/CategoryCreate.php @@ -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"; + } } } @@ -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;