1
0
mirror of https://github.com/moodle/moodle.git synced 2025-05-13 19:56:25 +02:00

MDL-83892 core_course: activity record from cm_info

Adds a new get_instance_record in the cm_info object so core can get the
activity table record without using the $DB object every time. Also, the
method caches de result so getting more than once per execution is much
faster.
This commit is contained in:
ferran 2025-01-24 14:26:57 +01:00
parent 7a318d5c85
commit c1e8684813
3 changed files with 64 additions and 0 deletions

@ -0,0 +1,9 @@
issueNumber: MDL-83892
notes:
core:
- message: >-
A new method get_instance_record has been added to cm_info object so
core can get the activity table record without using the $DB object
every time. Also, the method caches de result so getting more than once
per execution is much faster.
type: improved

@ -1481,6 +1481,12 @@ class cm_info implements IteratorAggregate {
*/
private $iconcomponent;
/**
* The instance record form the module table
* @var stdClass
*/
private $instancerecord;
/**
* Name of module e.g. 'forum' (this is the same name as the module's main database
* table) - from cached data in modinfo field
@ -2216,6 +2222,25 @@ class cm_info implements IteratorAggregate {
return $cmrecord;
}
/**
* Return the activity database table record.
*
* The instance record will be cached after the first call.
*
* @return stdClass
*/
public function get_instance_record() {
global $DB;
if (!isset($this->instancerecord)) {
$this->instancerecord = $DB->get_record(
table: $this->modname,
conditions: ['id' => $this->instance],
strictness: MUST_EXIST,
);
}
return $this->instancerecord;
}
/**
* Returns the section delegated by this module, if any.
*

@ -2240,4 +2240,34 @@ final class modinfolib_test extends advanced_testcase {
$cms = $sectioninfo->get_sequence_cm_infos();
$this->assertCount(0, $cms);
}
/**
* Test for cm_info::get_instance_record
*
* @covers \cm_info::get_instance_record
* @return void
*/
public function test_section_get_instance_record(): void {
global $DB;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course(['numsections' => 2]);
$activity = $this->getDataGenerator()->create_module('page', ['course' => $course], ['section' => 0]);
$modinfo = get_fast_modinfo($course->id);
$cminfo = $modinfo->get_cm($activity->cmid);
$instancerecord = $DB->get_record('page', ['id' => $activity->id]);
$instance = $cminfo->get_instance_record();
$this->assertEquals($instancerecord, $instance);
// The instance record should be cached.
$DB->delete_records('page', ['id' => $activity->id]);
$instance2 = $cminfo->get_instance_record();
$this->assertEquals($instancerecord, $instance);
$this->assertEquals($instance, $instance2);
}
}