Skip to content

Commit

Permalink
refactor to db pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
Glutamat42 committed Sep 30, 2024
1 parent d2c3005 commit a540483
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 10 deletions.
10 changes: 10 additions & 0 deletions classes/local/db/moodle_core_repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,14 @@ public function update_grade_item_record(int $grade_item_id, array $data): void
public function update_course_module_record(int $cmid, array $data): void {
$this->db->update_record('course_modules', (object)array_merge($data, ['id' => $cmid]));
}

public function get_cms_with_module_name_by_course_id(int $course_id): array {
return $this->db->get_records_sql(
'SELECT cm.*, m.name AS modname
FROM {course_modules} cm
JOIN {modules} m ON m.id = cm.module
WHERE cm.course = ?',
[$course_id]
);
}
}
11 changes: 1 addition & 10 deletions classes/local/upgrade/upgrade_3_2_0_to_4_0_0_completionlib.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,7 @@ private function resetCourseCache(): void {
*/
public function upgrade_modules(): void {
global $DB;
// get_fast_modinfo is not allowed during upgrade and there is no get_modinfo
// TODO: probably always follow this approach
// TODO: repo pattern
$cm_infos = $DB->get_records_sql(
'SELECT cm.*, m.name AS modname
FROM {course_modules} cm
JOIN {modules} m ON m.id = cm.module
WHERE cm.course = ?',
[$this->course_id]
);
$cm_infos = $this->moodle_core_repository->get_cms_with_module_name_by_course_id($this->course_id);

$transaction = $DB->start_delegated_transaction();
foreach ($cm_infos as $cm_info) {
Expand Down
18 changes: 18 additions & 0 deletions tests/local/db/moodle_core_repository_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,22 @@ public function test_update_course_module_record() {
$result = $DB->get_record('course_modules', ['id' => $course_module->cmid]);
$this->assertEquals(2, $result->completion);
}

public function test_get_cms_with_module_name_by_course_id() {
$moodle_core_repository = new moodle_core_repository();

// Create a course
$course = $this->getDataGenerator()->create_course();

// Create a course module
$course_module = $this->getDataGenerator()->create_module('url', ['course' => $course->id]);

// Call the function
$result = $moodle_core_repository->get_cms_with_module_name_by_course_id($course->id);

// Check the result
$this->assertCount(1, $result);
$this->assertEquals($course_module->id, reset($result)->instance);
$this->assertEquals('url', reset($result)->modname);
}
}

0 comments on commit a540483

Please sign in to comment.