MDL-43820 enrol_self: Override find_instance

This one is bit tricky. find_instance will find first available since
results are not unique...
This commit is contained in:
Ilya Tregubov 2023-08-08 15:51:24 +08:00
parent 200886f8a6
commit b70c7b141f
No known key found for this signature in database
GPG Key ID: 0F58186F748E55C1
2 changed files with 50 additions and 0 deletions

View File

@ -1088,6 +1088,28 @@ class enrol_self_plugin extends enrol_plugin {
public function is_csv_upload_supported(): bool {
return true;
}
/**
* Finds matching instances for a given course.
*
* @param array $enrolmentdata enrolment data.
* @param int $courseid Course ID.
* @return stdClass|null Matching instance
*/
public function find_instance(array $enrolmentdata, int $courseid) : ?stdClass {
$instances = enrol_get_instances($courseid, false);
$instance = null;
foreach ($instances as $i) {
if ($i->enrol == 'self') {
// This is bad - we can not really distinguish between self instances. So grab first available.
$instance = $i;
break;
}
}
return $instance;
}
}
/**

View File

@ -961,4 +961,32 @@ class self_test extends \advanced_testcase {
// Self enrol has 2 enrol actions -- edit and unenrol.
$this->assertCount(2, $actions);
}
/**
* Test the behaviour of find_instance().
*
* @covers ::find_instance
*/
public function test_find_instance() {
global $DB;
$this->resetAfterTest();
$cat = $this->getDataGenerator()->create_category();
// When we create a course, a self enrolment instance is also created.
$course = $this->getDataGenerator()->create_course(['category' => $cat->id, 'shortname' => 'ANON']);
$teacherrole = $DB->get_record('role', ['shortname' => 'teacher']);
$selfplugin = enrol_get_plugin('self');
$instanceid1 = $DB->get_record('enrol', ['courseid' => $course->id, 'enrol' => 'self']);
// Let's add a second instance.
$instanceid2 = $selfplugin->add_instance($course, ['roleid' => $teacherrole->id]);
$enrolmentdata = [];
// The first instance should be returned - due to sorting in enrol_get_instances().
$actual = $selfplugin->find_instance($enrolmentdata, $course->id);
$this->assertEquals($instanceid1->id, $actual->id);
}
}