MDL-60028 enrol: fix counting of enrolled users in a given context.

Previously users enrolled in a course via multiple enrolment methods
would be counted multiple times.
This commit is contained in:
Paul Holden 2018-09-07 14:18:45 +01:00
parent 6902f39141
commit f56e695883
2 changed files with 42 additions and 1 deletions

View File

@ -751,4 +751,45 @@ class core_enrollib_testcase extends advanced_testcase {
$this->assertCount(2, enrol_get_course_users($course1->id, false));
$this->assertCount(1, enrol_get_course_users($course1->id, true));
}
/**
* Test count of enrolled users
*
* @return void
*/
public function test_count_enrolled_users() {
global $DB;
$this->resetAfterTest(true);
$course = $this->getDataGenerator()->create_course();
$context = \context_course::instance($course->id);
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$studentrole = $DB->get_record('role', ['shortname' => 'student']);
// Add each user to the manual enrolment instance.
$manual = enrol_get_plugin('manual');
$manualinstance = $DB->get_record('enrol', ['courseid' => $course->id, 'enrol' => 'manual'], '*', MUST_EXIST);
$manual->enrol_user($manualinstance, $user1->id, $studentrole->id);
$manual->enrol_user($manualinstance, $user2->id, $studentrole->id);
$this->assertEquals(2, count_enrolled_users($context));
// Create a self enrolment instance, enrol first user only.
$self = enrol_get_plugin('self');
$selfid = $self->add_instance($course,
['status' => ENROL_INSTANCE_ENABLED, 'name' => 'Self', 'customint6' => 1, 'roleid' => $studentrole->id]);
$selfinstance = $DB->get_record('enrol', ['id' => $selfid], '*', MUST_EXIST);
$self->enrol_user($selfinstance, $user1->id, $studentrole->id);
// There are still only two distinct users.
$this->assertEquals(2, count_enrolled_users($context));
}
}

View File

@ -1505,7 +1505,7 @@ function count_enrolled_users(context $context, $withcapability = '', $groupid =
$capjoin = get_enrolled_with_capabilities_join(
$context, '', $withcapability, $groupid, $onlyactive);
$sql = "SELECT count(u.id)
$sql = "SELECT COUNT(DISTINCT u.id)
FROM {user} u
$capjoin->joins
WHERE $capjoin->wheres AND u.deleted = 0";