Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace core;
18
 
19
/**
20
 * Test for various bits of datalib.php.
21
 *
22
 * @package   core
23
 * @category  test
24
 * @copyright 2012 The Open University
25
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26
 */
1441 ariadna 27
final class datalib_test extends \advanced_testcase {
1 efrain 28
    protected function normalise_sql($sort) {
29
        return preg_replace('~\s+~', ' ', $sort);
30
    }
31
 
32
    protected function assert_same_sql($expected, $actual) {
33
        $this->assertSame($this->normalise_sql($expected), $this->normalise_sql($actual));
34
    }
35
 
36
    /**
37
     * Do a test of the user search SQL with database users.
38
     */
11 efrain 39
    public function test_users_search_sql(): void {
1 efrain 40
        global $DB;
41
        $this->resetAfterTest();
42
 
43
        // Set up test users.
44
        $user1 = array(
45
            'username' => 'usernametest1',
46
            'idnumber' => 'idnumbertest1',
47
            'firstname' => 'First Name User Test 1',
48
            'lastname' => 'Last Name User Test 1',
49
            'email' => 'usertest1@example.com',
50
            'address' => '2 Test Street Perth 6000 WA',
51
            'phone1' => '01010101010',
52
            'phone2' => '02020203',
53
            'department' => 'Department of user 1',
54
            'institution' => 'Institution of user 1',
55
            'description' => 'This is a description for user 1',
56
            'descriptionformat' => FORMAT_MOODLE,
57
            'city' => 'Perth',
58
            'country' => 'AU'
59
            );
60
        $user1 = self::getDataGenerator()->create_user($user1);
61
        $user2 = array(
62
            'username' => 'usernametest2',
63
            'idnumber' => 'idnumbertest2',
64
            'firstname' => 'First Name User Test 2',
65
            'lastname' => 'Last Name User Test 2',
66
            'email' => 'usertest2@example.com',
67
            'address' => '222 Test Street Perth 6000 WA',
68
            'phone1' => '01010101010',
69
            'phone2' => '02020203',
70
            'department' => 'Department of user 2',
71
            'institution' => 'Institution of user 2',
72
            'description' => 'This is a description for user 2',
73
            'descriptionformat' => FORMAT_MOODLE,
74
            'city' => 'Perth',
75
            'country' => 'AU'
76
            );
77
        $user2 = self::getDataGenerator()->create_user($user2);
78
 
79
        // Search by name (anywhere in text).
80
        list($sql, $params) = users_search_sql('User Test 2', '', USER_SEARCH_CONTAINS);
81
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
82
        $this->assertFalse(array_key_exists($user1->id, $results));
83
        $this->assertTrue(array_key_exists($user2->id, $results));
84
 
85
        // Search by (most of) full name.
86
        list($sql, $params) = users_search_sql('First Name User Test 2 Last Name User', '', USER_SEARCH_CONTAINS);
87
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
88
        $this->assertFalse(array_key_exists($user1->id, $results));
89
        $this->assertTrue(array_key_exists($user2->id, $results));
90
 
91
        // Search by name (start of text) valid or not.
92
        list($sql, $params) = users_search_sql('User Test 2', '');
93
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
94
        $this->assertEquals(0, count($results));
95
        list($sql, $params) = users_search_sql('First Name User Test 2', '');
96
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
97
        $this->assertFalse(array_key_exists($user1->id, $results));
98
        $this->assertTrue(array_key_exists($user2->id, $results));
99
 
100
        // Search by extra fields included or not (address).
101
        list($sql, $params) = users_search_sql('Test Street', '', USER_SEARCH_CONTAINS);
102
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
103
        $this->assertCount(0, $results);
104
        list($sql, $params) = users_search_sql('Test Street', '', USER_SEARCH_CONTAINS, array('address'));
105
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
106
        $this->assertCount(2, $results);
107
 
108
        // Exclude user.
109
        list($sql, $params) = users_search_sql('User Test', '', USER_SEARCH_CONTAINS, array(), array($user1->id));
110
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
111
        $this->assertFalse(array_key_exists($user1->id, $results));
112
        $this->assertTrue(array_key_exists($user2->id, $results));
113
 
114
        // Include only user.
115
        list($sql, $params) = users_search_sql('User Test', '', USER_SEARCH_CONTAINS, array(), array(), array($user1->id));
116
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
117
        $this->assertTrue(array_key_exists($user1->id, $results));
118
        $this->assertFalse(array_key_exists($user2->id, $results));
119
 
120
        // Exact match only.
121
        [$sql, $params] = users_search_sql('Last Name User Test 1', '', USER_SEARCH_EXACT_MATCH, [], null, null, true);
122
        $results = $DB->get_records_sql("SELECT id FROM {user} WHERE $sql ORDER BY username", $params);
123
        $this->assertTrue(array_key_exists($user1->id, $results));
124
        $this->assertFalse(array_key_exists($user2->id, $results));
125
 
126
        // Join with another table and use different prefix.
127
        set_user_preference('amphibian', 'frog', $user1);
128
        set_user_preference('amphibian', 'salamander', $user2);
129
        list($sql, $params) = users_search_sql('User Test 1', 'qq', USER_SEARCH_CONTAINS);
130
        $results = $DB->get_records_sql("
131
                SELECT up.id, up.value
132
                  FROM {user} qq
133
                  JOIN {user_preferences} up ON up.userid = qq.id
134
                 WHERE up.name = :prefname
135
                       AND $sql", array_merge(array('prefname' => 'amphibian'), $params));
136
        $this->assertEquals(1, count($results));
137
        foreach ($results as $record) {
138
            $this->assertSame('frog', $record->value);
139
        }
140
 
141
        // Join with another table and include other table fields in search.
142
        set_user_preference('reptile', 'snake', $user1);
143
        set_user_preference('reptile', 'lizard', $user2);
144
        list($sql, $params) = users_search_sql('snake', 'qq', USER_SEARCH_CONTAINS, ['up.value']);
145
        $results = $DB->get_records_sql("
146
                SELECT up.id, up.value
147
                  FROM {user} qq
148
                  JOIN {user_preferences} up ON up.userid = qq.id
149
                 WHERE up.name = :prefname
150
                       AND $sql", array_merge(array('prefname' => 'reptile'), $params));
151
        $this->assertEquals(1, count($results));
152
        foreach ($results as $record) {
153
            $this->assertSame('snake', $record->value);
154
        }
155
    }
156
 
11 efrain 157
    public function test_users_order_by_sql_simple(): void {
1 efrain 158
        list($sort, $params) = users_order_by_sql();
159
        $this->assert_same_sql('lastname, firstname, id', $sort);
160
        $this->assertEquals(array(), $params);
161
    }
162
 
11 efrain 163
    public function test_users_order_by_sql_table_prefix(): void {
1 efrain 164
        list($sort, $params) = users_order_by_sql('u');
165
        $this->assert_same_sql('u.lastname, u.firstname, u.id', $sort);
166
        $this->assertEquals(array(), $params);
167
    }
168
 
11 efrain 169
    public function test_users_order_by_sql_search_no_extra_fields(): void {
1 efrain 170
        global $CFG, $DB;
171
        $this->resetAfterTest(true);
172
 
173
        $CFG->showuseridentity = '';
174
 
175
        list($sort, $params) = users_order_by_sql('', 'search', \context_system::instance());
176
        $this->assert_same_sql('CASE WHEN
1441 ariadna 177
                    ' . $DB->sql_fullname() . ' = :usersortexact OR
178
                    LOWER(firstname) = LOWER(:usersortfield0) OR
179
                    LOWER(lastname) = LOWER(:usersortfield1)
1 efrain 180
                THEN 0 ELSE 1 END, lastname, firstname, id', $sort);
1441 ariadna 181
        $this->assertEquals(['usersortexact' => 'search', 'usersortfield0' => 'search', 'usersortfield1' => 'search'], $params);
1 efrain 182
    }
183
 
11 efrain 184
    public function test_users_order_by_sql_search_with_extra_fields_and_prefix(): void {
1 efrain 185
        global $CFG, $DB;
186
        $this->resetAfterTest();
187
 
188
        $CFG->showuseridentity = 'email,idnumber';
189
        $this->setAdminUser();
190
 
191
        list($sort, $params) = users_order_by_sql('u', 'search', \context_system::instance());
192
        $this->assert_same_sql('CASE WHEN
1441 ariadna 193
                    ' . $DB->sql_fullname('u.firstname', 'u.lastname') . ' = :usersortexact OR
194
                    LOWER(u.firstname) = LOWER(:usersortfield0) OR
195
                    LOWER(u.lastname) = LOWER(:usersortfield1) OR
196
                    LOWER(u.email) = LOWER(:usersortfield2) OR
197
                    LOWER(u.idnumber) = LOWER(:usersortfield3)
1 efrain 198
                THEN 0 ELSE 1 END, u.lastname, u.firstname, u.id', $sort);
1441 ariadna 199
        $this->assertEquals(['usersortexact' => 'search', 'usersortfield0' => 'search',
200
                'usersortfield1' => 'search', 'usersortfield2' => 'search', 'usersortfield3' => 'search'], $params);
1 efrain 201
    }
202
 
203
    public function test_users_order_by_sql_search_with_custom_fields(): void {
204
        global $CFG, $DB;
205
        $this->resetAfterTest();
206
 
207
        $CFG->showuseridentity = 'email,idnumber';
208
        $this->setAdminUser();
209
 
210
        list($sort, $params) =
211
                users_order_by_sql('u', 'search', \context_system::instance(), ['profile_field_customfield' => 'x.customfield']);
212
        $this->assert_same_sql('CASE WHEN
1441 ariadna 213
                    ' . $DB->sql_fullname('u.firstname', 'u.lastname') . ' = :usersortexact OR
214
                    LOWER(u.firstname) = LOWER(:usersortfield0) OR
215
                    LOWER(u.lastname) = LOWER(:usersortfield1) OR
216
                    LOWER(x.customfield) = LOWER(:usersortfield2)
1 efrain 217
                THEN 0 ELSE 1 END, u.lastname, u.firstname, u.id', $sort);
1441 ariadna 218
        $this->assertEquals(['usersortexact' => 'search', 'usersortfield0' => 'search',
219
                'usersortfield1' => 'search', 'usersortfield2' => 'search'], $params);
1 efrain 220
    }
221
 
11 efrain 222
    public function test_get_admin(): void {
1 efrain 223
        global $CFG, $DB;
224
        $this->resetAfterTest();
225
 
226
        $this->assertSame('2', $CFG->siteadmins); // Admin always has id 2 in new installs.
227
        $defaultadmin = get_admin();
228
        $this->assertEquals($defaultadmin->id, 2);
229
 
230
        unset_config('siteadmins');
231
        $this->assertFalse(get_admin());
232
 
233
        set_config('siteadmins', -1);
234
        $this->assertFalse(get_admin());
235
 
236
        $user1 = $this->getDataGenerator()->create_user();
237
        $user2 = $this->getDataGenerator()->create_user();
238
 
239
        set_config('siteadmins', $user1->id.','.$user2->id);
240
        $admin = get_admin();
241
        $this->assertEquals($user1->id, $admin->id);
242
 
243
        set_config('siteadmins', '-1,'.$user2->id.','.$user1->id);
244
        $admin = get_admin();
245
        $this->assertEquals($user2->id, $admin->id);
246
 
247
        $odlread = $DB->perf_get_reads();
248
        get_admin(); // No DB queries on repeated call expected.
249
        get_admin();
250
        get_admin();
251
        $this->assertEquals($odlread, $DB->perf_get_reads());
252
    }
253
 
11 efrain 254
    public function test_get_admins(): void {
1 efrain 255
        global $CFG, $DB;
256
        $this->resetAfterTest();
257
 
258
        $this->assertSame('2', $CFG->siteadmins); // Admin always has id 2 in new installs.
259
 
260
        $user1 = $this->getDataGenerator()->create_user();
261
        $user2 = $this->getDataGenerator()->create_user();
262
        $user3 = $this->getDataGenerator()->create_user();
263
        $user4 = $this->getDataGenerator()->create_user();
264
 
265
        $admins = get_admins();
266
        $this->assertCount(1, $admins);
267
        $admin = reset($admins);
268
        $this->assertTrue(isset($admins[$admin->id]));
269
        $this->assertEquals(2, $admin->id);
270
 
271
        unset_config('siteadmins');
272
        $this->assertSame(array(), get_admins());
273
 
274
        set_config('siteadmins', -1);
275
        $this->assertSame(array(), get_admins());
276
 
277
        set_config('siteadmins', '-1,'.$user2->id.','.$user1->id.','.$user3->id);
278
        $this->assertEquals(array($user2->id=>$user2, $user1->id=>$user1, $user3->id=>$user3), get_admins());
279
 
280
        $odlread = $DB->perf_get_reads();
281
        get_admins(); // This should make just one query.
282
        $this->assertEquals($odlread+1, $DB->perf_get_reads());
283
    }
284
 
11 efrain 285
    public function test_get_course(): void {
1 efrain 286
        global $DB, $PAGE, $SITE;
287
        $this->resetAfterTest();
288
 
289
        // First test course will be current course ($COURSE).
290
        $course1obj = $this->getDataGenerator()->create_course(array('shortname' => 'FROGS'));
291
        $PAGE->set_course($course1obj);
292
 
293
        // Second test course is not current course.
294
        $course2obj = $this->getDataGenerator()->create_course(array('shortname' => 'ZOMBIES'));
295
 
296
        // Check it does not make any queries when requesting the $COURSE/$SITE.
297
        $before = $DB->perf_get_queries();
298
        $result = get_course($course1obj->id);
299
        $this->assertEquals($before, $DB->perf_get_queries());
300
        $this->assertSame('FROGS', $result->shortname);
301
        $result = get_course($SITE->id);
302
        $this->assertEquals($before, $DB->perf_get_queries());
303
 
304
        // Check it makes 1 query to request other courses.
305
        $result = get_course($course2obj->id);
306
        $this->assertSame('ZOMBIES', $result->shortname);
307
        $this->assertEquals($before + 1, $DB->perf_get_queries());
308
    }
309
 
310
    /**
311
     * Test that specifying fields when calling get_courses always returns required fields "id, category, visible"
312
     */
313
    public function test_get_courses_with_fields(): void {
314
        $this->resetAfterTest();
315
 
316
        $category = $this->getDataGenerator()->create_category();
317
        $course = $this->getDataGenerator()->create_course(['category' => $category->id]);
318
 
319
        // Specify "id" only.
320
        $courses = get_courses($category->id, 'c.sortorder', 'c.id');
321
        $this->assertCount(1, $courses);
322
        $this->assertEquals((object) [
323
            'id' => $course->id,
324
            'category' => $course->category,
325
            'visible' => $course->visible,
326
        ], reset($courses));
327
 
328
        // Specify some optional fields.
329
        $courses = get_courses($category->id, 'c.sortorder', 'c.id, c.shortname, c.fullname');
330
        $this->assertCount(1, $courses);
331
        $this->assertEquals((object) [
332
            'id' => $course->id,
333
            'category' => $course->category,
334
            'visible' => $course->visible,
335
            'shortname' => $course->shortname,
336
            'fullname' => $course->fullname,
337
        ], reset($courses));
338
    }
339
 
11 efrain 340
    public function test_increment_revision_number(): void {
1 efrain 341
        global $DB;
342
        $this->resetAfterTest();
343
 
344
        // Use one of the fields that are used with increment_revision_number().
345
        $course1 = $this->getDataGenerator()->create_course();
346
        $course2 = $this->getDataGenerator()->create_course();
347
        $DB->set_field('course', 'cacherev', 1, array());
348
 
349
        $record1 = $DB->get_record('course', array('id'=>$course1->id));
350
        $record2 = $DB->get_record('course', array('id'=>$course2->id));
351
        $this->assertEquals(1, $record1->cacherev);
352
        $this->assertEquals(1, $record2->cacherev);
353
 
354
        // Incrementing some lower value.
355
        $this->setCurrentTimeStart();
356
        increment_revision_number('course', 'cacherev', 'id = :id', array('id'=>$course1->id));
357
        $record1 = $DB->get_record('course', array('id'=>$course1->id));
358
        $record2 = $DB->get_record('course', array('id'=>$course2->id));
359
        $this->assertTimeCurrent($record1->cacherev);
360
        $this->assertEquals(1, $record2->cacherev);
361
 
362
        // Incrementing in the same second.
363
        $rev1 = $DB->get_field('course', 'cacherev', array('id'=>$course1->id));
364
        $now = time();
365
        $DB->set_field('course', 'cacherev', $now, array('id'=>$course1->id));
366
        increment_revision_number('course', 'cacherev', 'id = :id', array('id'=>$course1->id));
367
        $rev2 = $DB->get_field('course', 'cacherev', array('id'=>$course1->id));
368
        $this->assertGreaterThan($rev1, $rev2);
369
        increment_revision_number('course', 'cacherev', 'id = :id', array('id'=>$course1->id));
370
        $rev3 = $DB->get_field('course', 'cacherev', array('id'=>$course1->id));
371
        $this->assertGreaterThan($rev2, $rev3);
372
        $this->assertGreaterThan($now+1, $rev3);
373
        increment_revision_number('course', 'cacherev', 'id = :id', array('id'=>$course1->id));
374
        $rev4 = $DB->get_field('course', 'cacherev', array('id'=>$course1->id));
375
        $this->assertGreaterThan($rev3, $rev4);
376
        $this->assertGreaterThan($now+2, $rev4);
377
 
378
        // Recovering from runaway revision.
379
        $DB->set_field('course', 'cacherev', time()+60*60*60, array('id'=>$course2->id));
380
        $record2 = $DB->get_record('course', array('id'=>$course2->id));
381
        $this->assertGreaterThan(time(), $record2->cacherev);
382
        $this->setCurrentTimeStart();
383
        increment_revision_number('course', 'cacherev', 'id = :id', array('id'=>$course2->id));
384
        $record2b = $DB->get_record('course', array('id'=>$course2->id));
385
        $this->assertTimeCurrent($record2b->cacherev);
386
 
387
        // Update all revisions.
388
        $DB->set_field('course', 'cacherev', 1, array());
389
        $this->setCurrentTimeStart();
390
        increment_revision_number('course', 'cacherev', '');
391
        $record1 = $DB->get_record('course', array('id'=>$course1->id));
392
        $record2 = $DB->get_record('course', array('id'=>$course2->id));
393
        $this->assertTimeCurrent($record1->cacherev);
394
        $this->assertEquals($record1->cacherev, $record2->cacherev);
395
    }
396
 
11 efrain 397
    public function test_get_coursemodule_from_id(): void {
1 efrain 398
        global $CFG;
399
 
400
        $this->resetAfterTest();
401
        $this->setAdminUser(); // Some generators have bogus access control.
402
 
403
        $this->assertFileExists("$CFG->dirroot/mod/folder/lib.php");
404
        $this->assertFileExists("$CFG->dirroot/mod/glossary/lib.php");
405
 
406
        $course1 = $this->getDataGenerator()->create_course();
407
        $course2 = $this->getDataGenerator()->create_course();
408
 
409
        $folder1a = $this->getDataGenerator()->create_module('folder', array('course' => $course1, 'section' => 3));
410
        $folder1b = $this->getDataGenerator()->create_module('folder', array('course' => $course1));
411
        $glossary1 = $this->getDataGenerator()->create_module('glossary', array('course' => $course1));
412
 
413
        $folder2 = $this->getDataGenerator()->create_module('folder', array('course' => $course2));
414
 
415
        $cm = get_coursemodule_from_id('folder', $folder1a->cmid);
416
        $this->assertInstanceOf('stdClass', $cm);
417
        $this->assertSame('folder', $cm->modname);
418
        $this->assertSame($folder1a->id, $cm->instance);
419
        $this->assertSame($folder1a->course, $cm->course);
420
        $this->assertObjectNotHasProperty('sectionnum', $cm);
421
 
422
        $this->assertEquals($cm, get_coursemodule_from_id('', $folder1a->cmid));
423
        $this->assertEquals($cm, get_coursemodule_from_id('folder', $folder1a->cmid, $course1->id));
424
        $this->assertEquals($cm, get_coursemodule_from_id('folder', $folder1a->cmid, 0));
425
        $this->assertFalse(get_coursemodule_from_id('folder', $folder1a->cmid, -10));
426
 
427
        $cm2 = get_coursemodule_from_id('folder', $folder1a->cmid, 0, true);
428
        $this->assertEquals(3, $cm2->sectionnum);
429
        unset($cm2->sectionnum);
430
        $this->assertEquals($cm, $cm2);
431
 
432
        $this->assertFalse(get_coursemodule_from_id('folder', -11));
433
 
434
        try {
435
            get_coursemodule_from_id('folder', -11, 0, false, MUST_EXIST);
436
            $this->fail('dml_missing_record_exception expected');
437
        } catch (\moodle_exception $e) {
438
            $this->assertInstanceOf('dml_missing_record_exception', $e);
439
        }
440
 
441
        try {
442
            get_coursemodule_from_id('', -11, 0, false, MUST_EXIST);
443
            $this->fail('dml_missing_record_exception expected');
444
        } catch (\moodle_exception $e) {
445
            $this->assertInstanceOf('dml_missing_record_exception', $e);
446
        }
447
 
448
        try {
449
            get_coursemodule_from_id('a b', $folder1a->cmid, 0, false, MUST_EXIST);
450
            $this->fail('coding_exception expected');
451
        } catch (\moodle_exception $e) {
452
            $this->assertInstanceOf('coding_exception', $e);
453
        }
454
 
455
        try {
456
            get_coursemodule_from_id('abc', $folder1a->cmid, 0, false, MUST_EXIST);
457
            $this->fail('dml_read_exception expected');
458
        } catch (\moodle_exception $e) {
459
            $this->assertInstanceOf('dml_read_exception', $e);
460
        }
461
    }
462
 
11 efrain 463
    public function test_get_coursemodule_from_instance(): void {
1 efrain 464
        global $CFG;
465
 
466
        $this->resetAfterTest();
467
        $this->setAdminUser(); // Some generators have bogus access control.
468
 
469
        $this->assertFileExists("$CFG->dirroot/mod/folder/lib.php");
470
        $this->assertFileExists("$CFG->dirroot/mod/glossary/lib.php");
471
 
472
        $course1 = $this->getDataGenerator()->create_course();
473
        $course2 = $this->getDataGenerator()->create_course();
474
 
475
        $folder1a = $this->getDataGenerator()->create_module('folder', array('course' => $course1, 'section' => 3));
476
        $folder1b = $this->getDataGenerator()->create_module('folder', array('course' => $course1));
477
 
478
        $folder2 = $this->getDataGenerator()->create_module('folder', array('course' => $course2));
479
 
480
        $cm = get_coursemodule_from_instance('folder', $folder1a->id);
481
        $this->assertInstanceOf('stdClass', $cm);
482
        $this->assertSame('folder', $cm->modname);
483
        $this->assertSame($folder1a->id, $cm->instance);
484
        $this->assertSame($folder1a->course, $cm->course);
485
        $this->assertObjectNotHasProperty('sectionnum', $cm);
486
 
487
        $this->assertEquals($cm, get_coursemodule_from_instance('folder', $folder1a->id, $course1->id));
488
        $this->assertEquals($cm, get_coursemodule_from_instance('folder', $folder1a->id, 0));
489
        $this->assertFalse(get_coursemodule_from_instance('folder', $folder1a->id, -10));
490
 
491
        $cm2 = get_coursemodule_from_instance('folder', $folder1a->id, 0, true);
492
        $this->assertEquals(3, $cm2->sectionnum);
493
        unset($cm2->sectionnum);
494
        $this->assertEquals($cm, $cm2);
495
 
496
        $this->assertFalse(get_coursemodule_from_instance('folder', -11));
497
 
498
        try {
499
            get_coursemodule_from_instance('folder', -11, 0, false, MUST_EXIST);
500
            $this->fail('dml_missing_record_exception expected');
501
        } catch (\moodle_exception $e) {
502
            $this->assertInstanceOf('dml_missing_record_exception', $e);
503
        }
504
 
505
        try {
506
            get_coursemodule_from_instance('a b', $folder1a->cmid, 0, false, MUST_EXIST);
507
            $this->fail('coding_exception expected');
508
        } catch (\moodle_exception $e) {
509
            $this->assertInstanceOf('coding_exception', $e);
510
        }
511
 
512
        try {
513
            get_coursemodule_from_instance('', $folder1a->cmid, 0, false, MUST_EXIST);
514
            $this->fail('coding_exception expected');
515
        } catch (\moodle_exception $e) {
516
            $this->assertInstanceOf('coding_exception', $e);
517
        }
518
 
519
        try {
520
            get_coursemodule_from_instance('abc', $folder1a->cmid, 0, false, MUST_EXIST);
521
            $this->fail('dml_read_exception expected');
522
        } catch (\moodle_exception $e) {
523
            $this->assertInstanceOf('dml_read_exception', $e);
524
        }
525
    }
526
 
11 efrain 527
    public function test_get_coursemodules_in_course(): void {
1 efrain 528
        global $CFG;
529
 
530
        $this->resetAfterTest();
531
        $this->setAdminUser(); // Some generators have bogus access control.
532
 
533
        $this->assertFileExists("$CFG->dirroot/mod/folder/lib.php");
534
        $this->assertFileExists("$CFG->dirroot/mod/glossary/lib.php");
535
        $this->assertFileExists("$CFG->dirroot/mod/label/lib.php");
536
 
537
        $course1 = $this->getDataGenerator()->create_course();
538
        $course2 = $this->getDataGenerator()->create_course();
539
 
540
        $folder1a = $this->getDataGenerator()->create_module('folder', array('course' => $course1, 'section' => 3));
541
        $folder1b = $this->getDataGenerator()->create_module('folder', array('course' => $course1));
542
        $glossary1 = $this->getDataGenerator()->create_module('glossary', array('course' => $course1));
543
 
544
        $folder2 = $this->getDataGenerator()->create_module('folder', array('course' => $course2));
545
        $glossary2a = $this->getDataGenerator()->create_module('glossary', array('course' => $course2));
546
        $glossary2b = $this->getDataGenerator()->create_module('glossary', array('course' => $course2));
547
 
548
        $modules = get_coursemodules_in_course('folder', $course1->id);
549
        $this->assertCount(2, $modules);
550
 
551
        $cm = $modules[$folder1a->cmid];
552
        $this->assertSame('folder', $cm->modname);
553
        $this->assertSame($folder1a->id, $cm->instance);
554
        $this->assertSame($folder1a->course, $cm->course);
555
        $this->assertObjectNotHasProperty('sectionnum', $cm);
556
        $this->assertObjectNotHasProperty('revision', $cm);
557
        $this->assertObjectNotHasProperty('display', $cm);
558
 
559
        $cm = $modules[$folder1b->cmid];
560
        $this->assertSame('folder', $cm->modname);
561
        $this->assertSame($folder1b->id, $cm->instance);
562
        $this->assertSame($folder1b->course, $cm->course);
563
        $this->assertObjectNotHasProperty('sectionnum', $cm);
564
        $this->assertObjectNotHasProperty('revision', $cm);
565
        $this->assertObjectNotHasProperty('display', $cm);
566
 
567
        $modules = get_coursemodules_in_course('folder', $course1->id, 'revision, display');
568
        $this->assertCount(2, $modules);
569
 
570
        $cm = $modules[$folder1a->cmid];
571
        $this->assertSame('folder', $cm->modname);
572
        $this->assertSame($folder1a->id, $cm->instance);
573
        $this->assertSame($folder1a->course, $cm->course);
574
        $this->assertObjectNotHasProperty('sectionnum', $cm);
575
        $this->assertObjectHasProperty('revision', $cm);
576
        $this->assertObjectHasProperty('display', $cm);
577
 
578
        $modules = get_coursemodules_in_course('label', $course1->id);
579
        $this->assertCount(0, $modules);
580
 
581
        try {
582
            get_coursemodules_in_course('a b', $course1->id);
583
            $this->fail('coding_exception expected');
584
        } catch (\moodle_exception $e) {
585
            $this->assertInstanceOf('coding_exception', $e);
586
        }
587
 
588
        try {
589
            get_coursemodules_in_course('abc', $course1->id);
590
            $this->fail('dml_read_exception expected');
591
        } catch (\moodle_exception $e) {
592
            $this->assertInstanceOf('dml_read_exception', $e);
593
        }
594
    }
595
 
11 efrain 596
    public function test_get_all_instances_in_courses(): void {
1 efrain 597
        global $CFG;
598
 
599
        $this->resetAfterTest();
600
        $this->setAdminUser(); // Some generators have bogus access control.
601
 
602
        $this->assertFileExists("$CFG->dirroot/mod/folder/lib.php");
603
        $this->assertFileExists("$CFG->dirroot/mod/glossary/lib.php");
604
 
605
        $course1 = $this->getDataGenerator()->create_course();
606
        $course2 = $this->getDataGenerator()->create_course();
607
        $course3 = $this->getDataGenerator()->create_course();
608
 
609
        $folder1a = $this->getDataGenerator()->create_module('folder', array('course' => $course1, 'section' => 3));
610
        $folder1b = $this->getDataGenerator()->create_module('folder', array('course' => $course1));
611
        $glossary1 = $this->getDataGenerator()->create_module('glossary', array('course' => $course1));
612
 
613
        $folder2 = $this->getDataGenerator()->create_module('folder', array('course' => $course2));
614
        $glossary2a = $this->getDataGenerator()->create_module('glossary', array('course' => $course2));
615
        $glossary2b = $this->getDataGenerator()->create_module('glossary', array('course' => $course2));
616
 
617
        $folder3 = $this->getDataGenerator()->create_module('folder', array('course' => $course3));
618
 
619
        $modules = get_all_instances_in_courses('folder', array($course1->id => $course1, $course2->id => $course2));
620
        $this->assertCount(3, $modules);
621
 
622
        foreach ($modules as $cm) {
623
            if ($folder1a->cmid == $cm->coursemodule) {
624
                $folder = $folder1a;
625
            } else if ($folder1b->cmid == $cm->coursemodule) {
626
                $folder = $folder1b;
627
            } else if ($folder2->cmid == $cm->coursemodule) {
628
                $folder = $folder2;
629
            } else {
630
                $this->fail('Unexpected cm'. $cm->coursemodule);
631
            }
632
            $this->assertSame($folder->name, $cm->name);
633
            $this->assertSame($folder->course, $cm->course);
634
        }
635
 
636
        try {
637
            get_all_instances_in_courses('a b', array($course1->id => $course1, $course2->id => $course2));
638
            $this->fail('coding_exception expected');
639
        } catch (\moodle_exception $e) {
640
            $this->assertInstanceOf('coding_exception', $e);
641
        }
642
 
643
        try {
644
            get_all_instances_in_courses('', array($course1->id => $course1, $course2->id => $course2));
645
            $this->fail('coding_exception expected');
646
        } catch (\moodle_exception $e) {
647
            $this->assertInstanceOf('coding_exception', $e);
648
        }
649
    }
650
 
11 efrain 651
    public function test_get_all_instances_in_course(): void {
1 efrain 652
        global $CFG;
653
 
654
        $this->resetAfterTest();
655
        $this->setAdminUser(); // Some generators have bogus access control.
656
 
657
        $this->assertFileExists("$CFG->dirroot/mod/folder/lib.php");
658
        $this->assertFileExists("$CFG->dirroot/mod/glossary/lib.php");
659
 
660
        $course1 = $this->getDataGenerator()->create_course();
661
        $course2 = $this->getDataGenerator()->create_course();
662
        $course3 = $this->getDataGenerator()->create_course();
663
 
664
        $folder1a = $this->getDataGenerator()->create_module('folder', array('course' => $course1, 'section' => 3));
665
        $folder1b = $this->getDataGenerator()->create_module('folder', array('course' => $course1));
666
        $glossary1 = $this->getDataGenerator()->create_module('glossary', array('course' => $course1));
667
 
668
        $folder2 = $this->getDataGenerator()->create_module('folder', array('course' => $course2));
669
        $glossary2a = $this->getDataGenerator()->create_module('glossary', array('course' => $course2));
670
        $glossary2b = $this->getDataGenerator()->create_module('glossary', array('course' => $course2));
671
 
672
        $folder3 = $this->getDataGenerator()->create_module('folder', array('course' => $course3));
673
 
674
        $modules = get_all_instances_in_course('folder', $course1);
675
        $this->assertCount(2, $modules);
676
 
677
        foreach ($modules as $cm) {
678
            if ($folder1a->cmid == $cm->coursemodule) {
679
                $folder = $folder1a;
680
            } else if ($folder1b->cmid == $cm->coursemodule) {
681
                $folder = $folder1b;
682
            } else {
683
                $this->fail('Unexpected cm'. $cm->coursemodule);
684
            }
685
            $this->assertSame($folder->name, $cm->name);
686
            $this->assertSame($folder->course, $cm->course);
687
        }
688
 
689
        try {
690
            get_all_instances_in_course('a b', $course1);
691
            $this->fail('coding_exception expected');
692
        } catch (\moodle_exception $e) {
693
            $this->assertInstanceOf('coding_exception', $e);
694
        }
695
 
696
        try {
697
            get_all_instances_in_course('', $course1);
698
            $this->fail('coding_exception expected');
699
        } catch (\moodle_exception $e) {
700
            $this->assertInstanceOf('coding_exception', $e);
701
        }
702
    }
703
 
704
    /**
705
     * Test max courses in category
706
     */
11 efrain 707
    public function test_max_courses_in_category(): void {
1 efrain 708
        global $CFG;
709
        $this->resetAfterTest();
710
 
711
        // Default settings.
712
        $this->assertEquals(MAX_COURSES_IN_CATEGORY, get_max_courses_in_category());
713
 
714
        // Misc category.
715
        $misc = \core_course_category::get_default();
716
        $this->assertEquals(MAX_COURSES_IN_CATEGORY, $misc->sortorder);
717
 
718
        $category1 = $this->getDataGenerator()->create_category();
719
        $category2 = $this->getDataGenerator()->create_category();
720
 
721
        // Check category sort orders.
722
        $this->assertEquals(MAX_COURSES_IN_CATEGORY, \core_course_category::get($misc->id)->sortorder);
723
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 2, \core_course_category::get($category1->id)->sortorder);
724
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 3, \core_course_category::get($category2->id)->sortorder);
725
 
726
        // Create courses.
727
        $course1 = $this->getDataGenerator()->create_course(['category' => $category1->id]);
728
        $course2 = $this->getDataGenerator()->create_course(['category' => $category2->id]);
729
        $course3 = $this->getDataGenerator()->create_course(['category' => $category1->id]);
730
        $course4 = $this->getDataGenerator()->create_course(['category' => $category2->id]);
731
 
732
        // Check course sort orders.
733
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 2 + 2, get_course($course1->id)->sortorder);
734
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 3 + 2, get_course($course2->id)->sortorder);
735
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 2 + 1, get_course($course3->id)->sortorder);
736
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 3 + 1, get_course($course4->id)->sortorder);
737
 
738
        // Increase max course in category.
739
        $CFG->maxcoursesincategory = 20000;
740
        $this->assertEquals(20000, get_max_courses_in_category());
741
 
742
        // The sort order has not yet fixed, these sort orders should be the same as before.
743
        // Categories.
744
        $this->assertEquals(MAX_COURSES_IN_CATEGORY, \core_course_category::get($misc->id)->sortorder);
745
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 2, \core_course_category::get($category1->id)->sortorder);
746
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 3, \core_course_category::get($category2->id)->sortorder);
747
        // Courses in category 1.
748
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 2 + 2, get_course($course1->id)->sortorder);
749
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 2 + 1, get_course($course3->id)->sortorder);
750
        // Courses in category 2.
751
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 3 + 2, get_course($course2->id)->sortorder);
752
        $this->assertEquals(MAX_COURSES_IN_CATEGORY * 3 + 1, get_course($course4->id)->sortorder);
753
 
754
        // Create new category so that the sort orders are applied.
755
        $category3 = $this->getDataGenerator()->create_category();
756
        // Categories.
757
        $this->assertEquals(20000, \core_course_category::get($misc->id)->sortorder);
758
        $this->assertEquals(20000 * 2, \core_course_category::get($category1->id)->sortorder);
759
        $this->assertEquals(20000 * 3, \core_course_category::get($category2->id)->sortorder);
760
        $this->assertEquals(20000 * 4, \core_course_category::get($category3->id)->sortorder);
761
        // Courses in category 1.
762
        $this->assertEquals(20000 * 2 + 2, get_course($course1->id)->sortorder);
763
        $this->assertEquals(20000 * 2 + 1, get_course($course3->id)->sortorder);
764
        // Courses in category 2.
765
        $this->assertEquals(20000 * 3 + 2, get_course($course2->id)->sortorder);
766
        $this->assertEquals(20000 * 3 + 1, get_course($course4->id)->sortorder);
767
    }
768
 
769
    /**
770
     * Test debug message for max courses in category
771
     */
11 efrain 772
    public function test_debug_max_courses_in_category(): void {
1 efrain 773
        global $CFG;
774
        $this->resetAfterTest();
775
 
776
        // Set to small value so that we can check the debug message.
777
        $CFG->maxcoursesincategory = 3;
778
        $this->assertEquals(3, get_max_courses_in_category());
779
 
780
        $category1 = $this->getDataGenerator()->create_category();
781
 
782
        // There is only one course, no debug message.
783
        $this->getDataGenerator()->create_course(['category' => $category1->id]);
784
        $this->assertDebuggingNotCalled();
785
        // There are two courses, no debug message.
786
        $this->getDataGenerator()->create_course(['category' => $category1->id]);
787
        $this->assertDebuggingNotCalled();
788
        // There is debug message when number of courses reaches the maximum number.
789
        $this->getDataGenerator()->create_course(['category' => $category1->id]);
790
        $this->assertDebuggingCalled("The number of courses (category id: $category1->id) has reached max number of courses " .
791
            "in a category (" . get_max_courses_in_category() . "). It will cause a sorting performance issue. " .
792
            "Please set higher value for \$CFG->maxcoursesincategory in config.php. " .
793
            "Please also make sure \$CFG->maxcoursesincategory * MAX_COURSE_CATEGORIES less than max integer. " .
794
            "See tracker issues: MDL-25669 and MDL-69573");
795
    }
796
 
797
    /**
798
     * Tests the get_users_listing function.
799
     */
800
    public function test_get_users_listing(): void {
801
        global $DB;
802
 
803
        $this->resetAfterTest();
804
 
805
        $generator = $this->getDataGenerator();
806
 
807
        // Set up profile field.
808
        $generator->create_custom_profile_field(['datatype' => 'text',
809
                'shortname' => 'specialid', 'name' => 'Special user id']);
810
 
811
        // Set up the show user identity option.
812
        set_config('showuseridentity', 'department,profile_field_specialid');
813
 
814
        // Get all the existing user ids (we're going to remove these from test results).
815
        $existingids = array_fill_keys($DB->get_fieldset_select('user', 'id', '1 = 1'), true);
816
 
817
        // Create some test user accounts.
818
        $userids = [];
819
        foreach (['a', 'b', 'c', 'd'] as $key) {
820
            $record = [
821
                'username' => 'user_' . $key,
822
                'firstname' => $key . '_first',
823
                'lastname' => 'last_' . $key,
824
                'department' => 'department_' . $key,
825
                'profile_field_specialid' => 'special_' . $key,
826
                'lastaccess' => ord($key)
827
            ];
828
            $user = $generator->create_user($record);
829
            $userids[] = $user->id;
830
        }
831
 
832
        // Check default result with no parameters.
833
        $results = get_users_listing();
834
        $results = array_diff_key($results, $existingids);
835
 
836
        // It should return all the results in order.
837
        $this->assertEquals($userids, array_keys($results));
838
 
839
        // Results should have some general fields and name fields, check some samples.
840
        $this->assertEquals('user_a', $results[$userids[0]]->username);
841
        $this->assertEquals('user_a@example.com', $results[$userids[0]]->email);
842
        $this->assertEquals(1, $results[$userids[0]]->confirmed);
843
        $this->assertEquals('a_first', $results[$userids[0]]->firstname);
844
        $this->assertObjectHasProperty('firstnamephonetic', $results[$userids[0]]);
845
 
846
        // Should not have the custom field or department because no context specified.
847
        $this->assertObjectNotHasProperty('department', $results[$userids[0]]);
848
        $this->assertObjectNotHasProperty('profile_field_specialid', $results[$userids[0]]);
849
 
850
        // Check sorting.
851
        $results = get_users_listing('username', 'DESC');
852
        $results = array_diff_key($results, $existingids);
853
        $this->assertEquals([$userids[3], $userids[2], $userids[1], $userids[0]], array_keys($results));
854
 
855
        // Check default fallback sort field works as expected.
856
        $results = get_users_listing('blah2', 'ASC');
857
        $results = array_diff_key($results, $existingids);
858
        $this->assertEquals([$userids[0], $userids[1], $userids[2], $userids[3]], array_keys($results));
859
 
860
        // Check default fallback sort direction works as expected.
861
        $results = get_users_listing('lastaccess', 'blah2');
862
        $results = array_diff_key($results, $existingids);
863
        $this->assertEquals([$userids[0], $userids[1], $userids[2], $userids[3]], array_keys($results));
864
 
865
        // Add the options to showuseridentity and check it returns those fields but only if you
866
        // specify a context AND have permissions.
867
        $results = get_users_listing('lastaccess', 'asc', 0, 0, '', '', '', '', null,
868
                \context_system::instance());
869
        $this->assertObjectNotHasProperty('department', $results[$userids[0]]);
870
        $this->assertObjectNotHasProperty('profile_field_specialid', $results[$userids[0]]);
871
        $this->setAdminUser();
872
        $results = get_users_listing('lastaccess', 'asc', 0, 0, '', '', '', '', null,
873
                \context_system::instance());
874
        $this->assertEquals('department_a', $results[$userids[0]]->department);
875
        $this->assertEquals('special_a', $results[$userids[0]]->profile_field_specialid);
876
 
877
        // Check search (full name, email, username).
878
        $results = get_users_listing('lastaccess', 'asc', 0, 0, 'b_first last_b');
879
        $this->assertEquals([$userids[1]], array_keys($results));
880
        $results = get_users_listing('lastaccess', 'asc', 0, 0, 'c@example');
881
        $this->assertEquals([$userids[2]], array_keys($results));
882
        $results = get_users_listing('lastaccess', 'asc', 0, 0, 'user_d');
883
        $this->assertEquals([$userids[3]], array_keys($results));
884
 
885
        // Check first and last initial restriction (all the test ones have same last initial).
886
        $results = get_users_listing('lastaccess', 'asc', 0, 0, '', 'C');
887
        $this->assertEquals([$userids[2]], array_keys($results));
888
        $results = get_users_listing('lastaccess', 'asc', 0, 0, '', '', 'L');
889
        $results = array_diff_key($results, $existingids);
890
        $this->assertEquals($userids, array_keys($results));
891
 
892
        // Check the extra where clause, either with the 'u.' prefix or not.
893
        $results = get_users_listing('lastaccess', 'asc', 0, 0, '', '', '', 'id IN (:x,:y)',
894
                ['x' => $userids[1], 'y' => $userids[3]]);
895
        $results = array_diff_key($results, $existingids);
896
        $this->assertEquals([$userids[1], $userids[3]], array_keys($results));
897
        $results = get_users_listing('lastaccess', 'asc', 0, 0, '', '', '', 'u.id IN (:x,:y)',
898
                ['x' => $userids[1], 'y' => $userids[3]]);
899
        $results = array_diff_key($results, $existingids);
900
        $this->assertEquals([$userids[1], $userids[3]], array_keys($results));
901
    }
902
 
903
    /**
904
     * Data provider for test_get_safe_orderby().
905
     *
906
     * @return array
907
     */
1441 ariadna 908
    public static function get_safe_orderby_provider(): array {
1 efrain 909
        $orderbymap = [
910
            'courseid' => 'c.id',
911
            'somecustomvalue' => 'c.startdate, c.shortname',
912
            'default' => 'c.fullname',
913
        ];
914
        $orderbymapnodefault = [
915
            'courseid' => 'c.id',
916
            'somecustomvalue' => 'c.startdate, c.shortname',
917
        ];
918
 
919
        return [
920
            'Valid option, no direction specified' => [
921
                $orderbymap,
922
                'somecustomvalue',
923
                '',
924
                ' ORDER BY c.startdate, c.shortname',
925
            ],
926
            'Valid option, valid direction specified' => [
927
                $orderbymap,
928
                'courseid',
929
                'DESC',
930
                ' ORDER BY c.id DESC',
931
            ],
932
            'Valid option, valid lowercase direction specified' => [
933
                $orderbymap,
934
                'courseid',
935
                'asc',
936
                ' ORDER BY c.id ASC',
937
            ],
938
            'Valid option, invalid direction specified' => [
939
                $orderbymap,
940
                'courseid',
941
                'BOOP',
942
                ' ORDER BY c.id',
943
            ],
944
            'Valid option, invalid lowercase direction specified' => [
945
                $orderbymap,
946
                'courseid',
947
                'boop',
948
                ' ORDER BY c.id',
949
            ],
950
            'Invalid option default fallback, with valid direction' => [
951
                $orderbymap,
952
                'thisdoesnotexist',
953
                'ASC',
954
                ' ORDER BY c.fullname ASC',
955
            ],
956
            'Invalid option default fallback, with invalid direction' => [
957
                $orderbymap,
958
                'thisdoesnotexist',
959
                'BOOP',
960
                ' ORDER BY c.fullname',
961
            ],
962
            'Invalid option without default, with valid direction' => [
963
                $orderbymapnodefault,
964
                'thisdoesnotexist',
965
                'ASC',
966
                '',
967
            ],
968
            'Invalid option without default, with invalid direction' => [
969
                $orderbymapnodefault,
970
                'thisdoesnotexist',
971
                'NOPE',
972
                '',
973
            ],
974
        ];
975
    }
976
 
977
    /**
978
     * Tests the get_safe_orderby function.
979
     *
980
     * @dataProvider get_safe_orderby_provider
981
     * @param array $orderbymap The ORDER BY parameter mapping array.
982
     * @param string $orderbykey The string key being provided, to check against the map.
983
     * @param string $direction The optional direction to order by.
984
     * @param string $expected The expected string output of the method.
985
     */
986
    public function test_get_safe_orderby(array $orderbymap, string $orderbykey, string $direction, string $expected): void {
987
        $actual = get_safe_orderby($orderbymap, $orderbykey, $direction);
988
        $this->assertEquals($expected, $actual);
989
    }
990
 
991
    /**
992
     * Data provider for test_get_safe_orderby_multiple().
993
     *
994
     * @return array
995
     */
1441 ariadna 996
    public static function get_safe_orderby_multiple_provider(): array {
1 efrain 997
        $orderbymap = [
998
            'courseid' => 'c.id',
999
            'firstname' => 'u.firstname',
1000
            'default' => 'c.startdate',
1001
        ];
1002
        $orderbymapnodefault = [
1003
            'courseid' => 'c.id',
1004
            'firstname' => 'u.firstname',
1005
        ];
1006
 
1007
        return [
1008
            'Valid options, no directions specified' => [
1009
                $orderbymap,
1010
                ['courseid', 'firstname'],
1011
                [],
1012
                ' ORDER BY c.id, u.firstname',
1013
            ],
1014
            'Valid options, some direction specified' => [
1015
                $orderbymap,
1016
                ['courseid', 'firstname'],
1017
                ['DESC'],
1018
                ' ORDER BY c.id DESC, u.firstname',
1019
            ],
1020
            'Valid options, all directions specified' => [
1021
                $orderbymap,
1022
                ['courseid', 'firstname'],
1023
                ['ASC', 'desc'],
1024
                ' ORDER BY c.id ASC, u.firstname DESC',
1025
            ],
1026
            'Valid options, valid and invalid directions specified' => [
1027
                $orderbymap,
1028
                ['courseid', 'firstname'],
1029
                ['BOOP', 'DESC'],
1030
                ' ORDER BY c.id, u.firstname DESC',
1031
            ],
1032
            'Valid options, all invalid directions specified' => [
1033
                $orderbymap,
1034
                ['courseid', 'firstname'],
1035
                ['BOOP', 'SNOOT'],
1036
                ' ORDER BY c.id, u.firstname',
1037
            ],
1038
            'Valid and invalid option default fallback, with valid directions' => [
1039
                $orderbymap,
1040
                ['thisdoesnotexist', 'courseid'],
1041
                ['asc', 'DESC'],
1042
                ' ORDER BY c.startdate ASC, c.id DESC',
1043
            ],
1044
            'Valid and invalid option default fallback, with invalid direction' => [
1045
                $orderbymap,
1046
                ['courseid', 'thisdoesnotexist'],
1047
                ['BOOP', 'SNOOT'],
1048
                ' ORDER BY c.id, c.startdate',
1049
            ],
1050
            'Valid and invalid option without default, with valid direction' => [
1051
                $orderbymapnodefault,
1052
                ['thisdoesnotexist', 'courseid'],
1053
                ['ASC', 'DESC'],
1054
                ' ORDER BY c.id DESC',
1055
            ],
1056
            'Valid and invalid option without default, with invalid direction' => [
1057
                $orderbymapnodefault,
1058
                ['thisdoesnotexist', 'courseid'],
1059
                ['BOOP', 'SNOOT'],
1060
                ' ORDER BY c.id',
1061
            ],
1062
            'Invalid option only without default, with valid direction' => [
1063
                $orderbymapnodefault,
1064
                ['thisdoesnotexist'],
1065
                ['ASC'],
1066
                '',
1067
            ],
1068
            'Invalid option only without default, with invalid direction' => [
1069
                $orderbymapnodefault,
1070
                ['thisdoesnotexist'],
1071
                ['BOOP'],
1072
                '',
1073
            ],
1074
            'Single valid option, direction specified' => [
1075
                $orderbymap,
1076
                ['firstname'],
1077
                ['ASC'],
1078
                ' ORDER BY u.firstname ASC',
1079
            ],
1080
            'Single valid option, direction not specified' => [
1081
                $orderbymap,
1082
                ['firstname'],
1083
                [],
1084
                ' ORDER BY u.firstname',
1085
            ],
1086
        ];
1087
    }
1088
 
1089
    /**
1090
     * Tests the get_safe_orderby_multiple function.
1091
     *
1092
     * @dataProvider get_safe_orderby_multiple_provider
1093
     * @param array $orderbymap The ORDER BY parameter mapping array.
1094
     * @param array $orderbykeys The array of string keys being provided, to check against the map.
1095
     * @param array $directions The optional directions to order by.
1096
     * @param string $expected The expected string output of the method.
1097
     */
1098
    public function test_get_safe_orderby_multiple(array $orderbymap, array $orderbykeys, array $directions,
1099
            string $expected): void {
1100
        $actual = get_safe_orderby_multiple($orderbymap, $orderbykeys, $directions);
1101
        $this->assertEquals($expected, $actual);
1102
    }
1103
}