From b70c7b141f2fa30decac588d8d46cb94d97f32e7 Mon Sep 17 00:00:00 2001 From: Ilya Tregubov Date: Tue, 8 Aug 2023 15:51:24 +0800 Subject: [PATCH] MDL-43820 enrol_self: Override find_instance This one is bit tricky. find_instance will find first available since results are not unique... --- enrol/self/lib.php | 22 ++++++++++++++++++++++ enrol/self/tests/self_test.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/enrol/self/lib.php b/enrol/self/lib.php index 7793ccb9f1a..ab838958b3c 100644 --- a/enrol/self/lib.php +++ b/enrol/self/lib.php @@ -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; + } + } /** diff --git a/enrol/self/tests/self_test.php b/enrol/self/tests/self_test.php index 351fdfeec34..53d2cc82d86 100644 --- a/enrol/self/tests/self_test.php +++ b/enrol/self/tests/self_test.php @@ -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); + } + }