MDL-50163 behat: Return subcontext from session
[moodle.git] / lib / tests / behat / behat_data_generators.php
CommitLineData
f0200d14 1<?php
f0200d14
DM
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/**
18 * Data generators for acceptance testing.
19 *
20 * @package core
21 * @category test
22 * @copyright 2012 David MonllaĆ³
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
28require_once(__DIR__ . '/../../behat/behat_base.php');
f0200d14
DM
29
30use Behat\Gherkin\Node\TableNode as TableNode;
31use Behat\Behat\Exception\PendingException as PendingException;
32
33/**
34 * Class to set up quickly a Given environment.
35 *
36 * Acceptance tests are block-boxed, so this steps definitions should only
37 * be used to set up the test environment as we are not replicating user steps.
38 *
d2eca4cd 39 * All data generators should be in lib/testing/generator/*, shared between phpunit
f0200d14 40 * and behat and they should be called from here, if possible using the standard
d2eca4cd
DM
41 * 'create_$elementname($options)' and if it's not possible (data generators arguments will not be
42 * always the same) or the element is not suitable to be a data generator, create a
43 * 'process_$elementname($options)' method and use the data generator from there if possible.
f0200d14
DM
44 *
45 * @todo If the available elements list grows too much this class must be split into smaller pieces
46 * @package core
47 * @category test
48 * @copyright 2012 David MonllaĆ³
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 */
51class behat_data_generators extends behat_base {
52
46ac40cd
DM
53 /**
54 * @var testing_data_generator
55 */
f0200d14
DM
56 protected $datagenerator;
57
58 /**
59 * Each element specifies:
60 * - The data generator sufix used.
61 * - The required fields.
62 * - The mapping between other elements references and database field names.
63 * @var array
64 */
65 protected static $elements = array(
66 'users' => array(
67 'datagenerator' => 'user',
68 'required' => array('username')
69 ),
70 'categories' => array(
71 'datagenerator' => 'category',
72 'required' => array('idnumber'),
73 'switchids' => array('category' => 'parent')
74 ),
75 'courses' => array(
76 'datagenerator' => 'course',
77 'required' => array('shortname'),
78 'switchids' => array('category' => 'category')
79 ),
80 'groups' => array(
81 'datagenerator' => 'group',
82 'required' => array('idnumber', 'course'),
83 'switchids' => array('course' => 'courseid')
84 ),
85 'groupings' => array(
86 'datagenerator' => 'grouping',
87 'required' => array('idnumber', 'course'),
88 'switchids' => array('course' => 'courseid')
89 ),
90 'course enrolments' => array(
91 'datagenerator' => 'enrol_user',
92 'required' => array('user', 'course', 'role'),
93 'switchids' => array('user' => 'userid', 'course' => 'courseid', 'role' => 'roleid')
f0200d14 94 ),
81cd8572
DM
95 'permission overrides' => array(
96 'datagenerator' => 'permission_override',
97 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
98 'switchids' => array('role' => 'roleid')
99 ),
d2eca4cd 100 'system role assigns' => array(
72ddc05f 101 'datagenerator' => 'system_role_assign',
d2eca4cd
DM
102 'required' => array('user', 'role'),
103 'switchids' => array('user' => 'userid', 'role' => 'roleid')
104 ),
72ddc05f
DM
105 'role assigns' => array(
106 'datagenerator' => 'role_assign',
107 'required' => array('user', 'role', 'contextlevel', 'reference'),
108 'switchids' => array('user' => 'userid', 'role' => 'roleid')
109 ),
a0902967
DM
110 'activities' => array(
111 'datagenerator' => 'activity',
112 'required' => array('activity', 'idnumber', 'course'),
15ace204 113 'switchids' => array('course' => 'course', 'gradecategory' => 'gradecat')
a0902967 114 ),
f0200d14
DM
115 'group members' => array(
116 'datagenerator' => 'group_member',
117 'required' => array('user', 'group'),
118 'switchids' => array('user' => 'userid', 'group' => 'groupid')
119 ),
120 'grouping groups' => array(
121 'datagenerator' => 'grouping_group',
122 'required' => array('grouping', 'group'),
123 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
23349a73
DM
124 ),
125 'cohorts' => array(
126 'datagenerator' => 'cohort',
127 'required' => array('idnumber')
702851c0 128 ),
9cc66e86
MG
129 'cohort members' => array(
130 'datagenerator' => 'cohort_member',
131 'required' => array('user', 'cohort'),
132 'switchids' => array('user' => 'userid', 'cohort' => 'cohortid')
133 ),
702851c0
DM
134 'roles' => array(
135 'datagenerator' => 'role',
136 'required' => array('shortname')
15ace204
DW
137 ),
138 'grade categories' => array(
139 'datagenerator' => 'grade_category',
140 'required' => array('fullname', 'course'),
141 'switchids' => array('course' => 'courseid', 'gradecategory' => 'parent')
cfa91962
JO
142 ),
143 'grade items' => array(
144 'datagenerator' => 'grade_item',
145 'required' => array('course'),
146 'switchids' => array('scale' => 'scaleid', 'outcome' => 'outcomeid', 'course' => 'courseid',
147 'gradecategory' => 'categoryid')
148 ),
149 'grade outcomes' => array(
150 'datagenerator' => 'grade_outcome',
151 'required' => array('shortname', 'scale'),
152 'switchids' => array('course' => 'courseid', 'gradecategory' => 'categoryid', 'scale' => 'scaleid')
153 ),
154 'scales' => array(
155 'datagenerator' => 'scale',
156 'required' => array('name', 'scale'),
157 'switchids' => array('course' => 'courseid')
0db16e08
TH
158 ),
159 'question categories' => array(
160 'datagenerator' => 'question_category',
161 'required' => array('name', 'contextlevel', 'reference'),
162 'switchids' => array('questioncategory' => 'category')
163 ),
164 'questions' => array(
165 'datagenerator' => 'question',
166 'required' => array('qtype', 'questioncategory', 'name'),
167 'switchids' => array('questioncategory' => 'category', 'user' => 'createdby')
168 ),
9a7e3986
MG
169 'tags' => array(
170 'datagenerator' => 'tag',
171 'required' => array('name')
172 ),
f0200d14
DM
173 );
174
175 /**
176 * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
177 *
c51c3b55 178 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
f0200d14
DM
179 *
180 * @throws Exception
181 * @throws PendingException
182 * @param string $elementname The name of the entity to add
183 * @param TableNode $data
184 */
c51c3b55 185 public function the_following_exist($elementname, TableNode $data) {
f0200d14 186
c29e3e24
DM
187 // Now that we need them require the data generators.
188 require_once(__DIR__ . '/../../testing/generator/lib.php');
189
f0200d14
DM
190 if (empty(self::$elements[$elementname])) {
191 throw new PendingException($elementname . ' data generator is not implemented');
192 }
193
194 $this->datagenerator = testing_util::get_data_generator();
195
196 $elementdatagenerator = self::$elements[$elementname]['datagenerator'];
197 $requiredfields = self::$elements[$elementname]['required'];
198 if (!empty(self::$elements[$elementname]['switchids'])) {
199 $switchids = self::$elements[$elementname]['switchids'];
200 }
201
202 foreach ($data->getHash() as $elementdata) {
203
204 // Check if all the required fields are there.
205 foreach ($requiredfields as $requiredfield) {
206 if (!isset($elementdata[$requiredfield])) {
207 throw new Exception($elementname . ' requires the field ' . $requiredfield . ' to be specified');
208 }
209 }
210
211 // Switch from human-friendly references to ids.
212 if (isset($switchids)) {
213 foreach ($switchids as $element => $field) {
214 $methodname = 'get_' . $element . '_id';
215
216 // Not all the switch fields are required, default vars will be assigned by data generators.
217 if (isset($elementdata[$element])) {
218 // Temp $id var to avoid problems when $element == $field.
219 $id = $this->{$methodname}($elementdata[$element]);
220 unset($elementdata[$element]);
221 $elementdata[$field] = $id;
222 }
223 }
224 }
225
226 // Preprocess the entities that requires a special treatment.
227 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
228 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
229 }
230
231 // Creates element.
232 $methodname = 'create_' . $elementdatagenerator;
233 if (method_exists($this->datagenerator, $methodname)) {
234 // Using data generators directly.
235 $this->datagenerator->{$methodname}($elementdata);
236
d2eca4cd
DM
237 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
238 // Using an alternative to the direct data generator call.
239 $this->{'process_' . $elementdatagenerator}($elementdata);
f0200d14
DM
240 } else {
241 throw new PendingException($elementname . ' data generator is not implemented');
242 }
243 }
244
245 }
246
247 /**
248 * If password is not set it uses the username.
249 * @param array $data
250 * @return array
251 */
252 protected function preprocess_user($data) {
253 if (!isset($data['password'])) {
254 $data['password'] = $data['username'];
255 }
256 return $data;
257 }
258
5f079af4
MG
259 /**
260 * If contextlevel and reference are specified for cohort, transform them to the contextid.
261 *
262 * @param array $data
263 * @return array
264 */
265 protected function preprocess_cohort($data) {
266 if (isset($data['contextlevel'])) {
267 if (!isset($data['reference'])) {
268 throw new Exception('If field contextlevel is specified, field reference must also be present');
269 }
270 $context = $this->get_context($data['contextlevel'], $data['reference']);
271 unset($data['contextlevel']);
272 unset($data['reference']);
273 $data['contextid'] = $context->id;
274 }
275 return $data;
276 }
277
cfa91962
JO
278 /**
279 * Preprocesses the creation of a grade item. Converts gradetype text to a number.
280 * @param array $data
281 * @return array
282 */
283 protected function preprocess_grade_item($data) {
284 global $CFG;
285 require_once("$CFG->libdir/grade/constants.php");
286
287 if (isset($data['gradetype'])) {
288 $data['gradetype'] = constant("GRADE_TYPE_" . strtoupper($data['gradetype']));
289 }
b13afc36
FM
290
291 if (!empty($data['category']) && !empty($data['courseid'])) {
292 $cat = grade_category::fetch(array('fullname' => $data['category'], 'courseid' => $data['courseid']));
293 if (!$cat) {
294 throw new Exception('Could not resolve category with name "' . $data['category'] . '"');
295 }
296 unset($data['category']);
297 $data['categoryid'] = $cat->id;
298 }
299
cfa91962
JO
300 return $data;
301 }
302
a0902967
DM
303 /**
304 * Adapter to modules generator
305 * @throws Exception Custom exception for test writers
306 * @param array $data
307 * @return void
308 */
309 protected function process_activity($data) {
cfa91962 310 global $DB, $CFG;
a0902967
DM
311
312 // The the_following_exists() method checks that the field exists.
313 $activityname = $data['activity'];
314 unset($data['activity']);
315
cfa91962
JO
316 // Convert scale name into scale id (negative number indicates using scale).
317 if (isset($data['grade']) && strlen($data['grade']) && !is_number($data['grade'])) {
318 $data['grade'] = - $this->get_scale_id($data['grade']);
319 require_once("$CFG->libdir/grade/constants.php");
320
321 if (!isset($data['gradetype'])) {
322 $data['gradetype'] = GRADE_TYPE_SCALE;
323 }
324 }
325
041cf62b
DM
326 // We split $data in the activity $record and the course module $options.
327 $cmoptions = array();
328 $cmcolumns = $DB->get_columns('course_modules');
329 foreach ($cmcolumns as $key => $value) {
330 if (isset($data[$key])) {
331 $cmoptions[$key] = $data[$key];
332 }
333 }
334
a0902967
DM
335 // Custom exception.
336 try {
041cf62b 337 $this->datagenerator->create_module($activityname, $data, $cmoptions);
a0902967
DM
338 } catch (coding_exception $e) {
339 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
340 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
341 }
342 }
f0200d14
DM
343
344 /**
345 * Adapter to enrol_user() data generator.
346 * @throws Exception
d2eca4cd 347 * @param array $data
f0200d14
DM
348 * @return void
349 */
d2eca4cd 350 protected function process_enrol_user($data) {
a8a48495 351 global $SITE;
f0200d14
DM
352
353 if (empty($data['roleid'])) {
354 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
355 }
356
357 if (!isset($data['userid'])) {
358 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
359 }
360
361 if (!isset($data['courseid'])) {
362 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
363 }
364
365 if (!isset($data['enrol'])) {
366 $data['enrol'] = 'manual';
367 }
368
2f29dd62
TB
369 if (!isset($data['timestart'])) {
370 $data['timestart'] = 0;
371 }
372
373 if (!isset($data['timeend'])) {
374 $data['timeend'] = 0;
375 }
376
377 if (!isset($data['status'])) {
378 $data['status'] = null;
379 }
380
a8a48495
DM
381 // If the provided course shortname is the site shortname we consider it a system role assign.
382 if ($data['courseid'] == $SITE->id) {
383 // Frontpage course assign.
384 $context = context_course::instance($data['courseid']);
385 role_assign($data['roleid'], $data['userid'], $context->id);
386
387 } else {
388 // Course assign.
2f29dd62
TB
389 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'],
390 $data['timestart'], $data['timeend'], $data['status']);
a8a48495
DM
391 }
392
f0200d14
DM
393 }
394
81cd8572
DM
395 /**
396 * Allows/denies a capability at the specified context
397 *
398 * @throws Exception
399 * @param array $data
400 * @return void
401 */
402 protected function process_permission_override($data) {
403
404 // Will throw an exception if it does not exist.
405 $context = $this->get_context($data['contextlevel'], $data['reference']);
406
407 switch ($data['permission']) {
a5254141 408 case get_string('allow', 'role'):
81cd8572
DM
409 $permission = CAP_ALLOW;
410 break;
a5254141 411 case get_string('prevent', 'role'):
81cd8572
DM
412 $permission = CAP_PREVENT;
413 break;
a5254141 414 case get_string('prohibit', 'role'):
81cd8572
DM
415 $permission = CAP_PROHIBIT;
416 break;
417 default:
418 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
419 break;
420 }
421
422 if (is_null(get_capability_info($data['capability']))) {
423 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
424 }
425
426 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
427 }
428
d2eca4cd 429 /**
72ddc05f
DM
430 * Assigns a role to a user at system context
431 *
432 * Used by "system role assigns" can be deleted when
433 * system role assign will be deprecated in favour of
434 * "role assigns"
435 *
d2eca4cd
DM
436 * @throws Exception
437 * @param array $data
438 * @return void
439 */
72ddc05f 440 protected function process_system_role_assign($data) {
d2eca4cd
DM
441
442 if (empty($data['roleid'])) {
443 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
444 }
445
446 if (!isset($data['userid'])) {
447 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
448 }
449
450 $context = context_system::instance();
72ddc05f
DM
451
452 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
453 }
454
455 /**
456 * Assigns a role to a user at the specified context
457 *
458 * @throws Exception
459 * @param array $data
460 * @return void
461 */
462 protected function process_role_assign($data) {
463
464 if (empty($data['roleid'])) {
465 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
466 }
467
468 if (!isset($data['userid'])) {
469 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
470 }
471
472 if (empty($data['contextlevel'])) {
473 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
474 }
475
476 if (!isset($data['reference'])) {
477 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
478 }
479
480 // Getting the context id.
481 $context = $this->get_context($data['contextlevel'], $data['reference']);
482
483 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
f0200d14
DM
484 }
485
702851c0
DM
486 /**
487 * Creates a role.
488 *
489 * @param array $data
490 * @return void
491 */
492 protected function process_role($data) {
493
494 // We require the user to fill the role shortname.
495 if (empty($data['shortname'])) {
496 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
497 }
498
499 $this->datagenerator->create_role($data);
500 }
501
9cc66e86
MG
502 /**
503 * Adds members to cohorts
504 *
505 * @param array $data
506 * @return void
507 */
508 protected function process_cohort_member($data) {
509 cohort_add_member($data['cohortid'], $data['userid']);
510 }
511
0db16e08
TH
512 /**
513 * Create a question category.
514 *
515 * @param array $data the row of data from the behat script.
516 */
517 protected function process_question_category($data) {
518 $context = $this->get_context($data['contextlevel'], $data['reference']);
519 $data['contextid'] = $context->id;
520 $this->datagenerator->get_plugin_generator('core_question')->create_question_category($data);
521 }
522
523 /**
524 * Create a question.
525 *
526 * Creating questions relies on the question/type/.../tests/helper.php mechanism.
527 * We start with test_question_maker::get_question_form_data($data['qtype'], $data['template'])
528 * and then overlay the values from any other fields of $data that are set.
529 *
530 * @param array $data the row of data from the behat script.
531 */
532 protected function process_question($data) {
533 if (array_key_exists('questiontext', $data)) {
534 $data['questiontext'] = array(
535 'text' => $data['questiontext'],
536 'format' => FORMAT_HTML,
537 );
538 }
539
540 if (array_key_exists('generalfeedback', $data)) {
541 $data['generalfeedback'] = array(
542 'text' => $data['generalfeedback'],
543 'format' => FORMAT_HTML,
544 );
545 }
546
547 $which = null;
548 if (!empty($data['template'])) {
549 $which = $data['template'];
550 }
551
552 $this->datagenerator->get_plugin_generator('core_question')->create_question($data['qtype'], $which, $data);
553 }
554
15ace204
DW
555 /**
556 * Gets the grade category id from the grade category fullname
557 * @throws Exception
558 * @param string $username
559 * @return int
560 */
561 protected function get_gradecategory_id($fullname) {
562 global $DB;
563
564 if (!$id = $DB->get_field('grade_categories', 'id', array('fullname' => $fullname))) {
565 throw new Exception('The specified grade category with fullname "' . $fullname . '" does not exist');
566 }
567 return $id;
568 }
569
f0200d14
DM
570 /**
571 * Gets the user id from it's username.
572 * @throws Exception
46ac40cd 573 * @param string $username
f0200d14
DM
574 * @return int
575 */
576 protected function get_user_id($username) {
577 global $DB;
578
579 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
1f9ffbdb 580 throw new Exception('The specified user with username "' . $username . '" does not exist');
f0200d14
DM
581 }
582 return $id;
583 }
584
585 /**
586 * Gets the role id from it's shortname.
587 * @throws Exception
46ac40cd 588 * @param string $roleshortname
f0200d14
DM
589 * @return int
590 */
591 protected function get_role_id($roleshortname) {
592 global $DB;
593
594 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
702851c0 595 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
f0200d14
DM
596 }
597
598 return $id;
599 }
600
601 /**
602 * Gets the category id from it's idnumber.
603 * @throws Exception
604 * @param string $idnumber
605 * @return int
606 */
607 protected function get_category_id($idnumber) {
608 global $DB;
609
610 // If no category was specified use the data generator one.
611 if ($idnumber == false) {
612 return null;
613 }
614
615 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 616 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
617 }
618
619 return $id;
620 }
621
622 /**
623 * Gets the course id from it's shortname.
624 * @throws Exception
625 * @param string $shortname
626 * @return int
627 */
628 protected function get_course_id($shortname) {
629 global $DB;
630
631 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
702851c0 632 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
f0200d14
DM
633 }
634 return $id;
635 }
636
637 /**
638 * Gets the group id from it's idnumber.
639 * @throws Exception
640 * @param string $idnumber
641 * @return int
642 */
643 protected function get_group_id($idnumber) {
644 global $DB;
645
646 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 647 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
648 }
649 return $id;
650 }
651
652 /**
653 * Gets the grouping id from it's idnumber.
654 * @throws Exception
655 * @param string $idnumber
656 * @return int
657 */
658 protected function get_grouping_id($idnumber) {
659 global $DB;
660
661 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 662 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
663 }
664 return $id;
665 }
72ddc05f 666
9cc66e86
MG
667 /**
668 * Gets the cohort id from it's idnumber.
669 * @throws Exception
670 * @param string $idnumber
671 * @return int
672 */
673 protected function get_cohort_id($idnumber) {
674 global $DB;
675
676 if (!$id = $DB->get_field('cohort', 'id', array('idnumber' => $idnumber))) {
677 throw new Exception('The specified cohort with idnumber "' . $idnumber . '" does not exist');
678 }
679 return $id;
680 }
681
cfa91962
JO
682 /**
683 * Gets the outcome item id from its shortname.
684 * @throws Exception
685 * @param string $shortname
686 * @return int
687 */
688 protected function get_outcome_id($shortname) {
689 global $DB;
690
691 if (!$id = $DB->get_field('grade_outcomes', 'id', array('shortname' => $shortname))) {
692 throw new Exception('The specified outcome with shortname "' . $shortname . '" does not exist');
693 }
694 return $id;
695 }
696
697 /**
0db16e08
TH
698 * Get the id of a named scale.
699 * @param string $name the name of the scale.
700 * @return int the scale id.
cfa91962
JO
701 */
702 protected function get_scale_id($name) {
703 global $DB;
704
705 if (!$id = $DB->get_field('scale', 'id', array('name' => $name))) {
706 throw new Exception('The specified scale with name "' . $name . '" does not exist');
707 }
708 return $id;
709 }
710
0db16e08
TH
711 /**
712 * Get the id of a named question category (must be globally unique).
713 * Note that 'Top' is a special value, used when setting the parent of another
714 * category, meaning top-level.
715 *
716 * @param string $name the question category name.
717 * @return int the question category id.
718 */
719 protected function get_questioncategory_id($name) {
720 global $DB;
721
722 if ($name == 'Top') {
723 return 0;
724 }
725
726 if (!$id = $DB->get_field('question_categories', 'id', array('name' => $name))) {
727 throw new Exception('The specified question category with name "' . $name . '" does not exist');
728 }
729 return $id;
730 }
731
72ddc05f
DM
732 /**
733 * Gets the internal context id from the context reference.
734 *
735 * The context reference changes depending on the context
736 * level, it can be the system, a user, a category, a course or
737 * a module.
738 *
739 * @throws Exception
740 * @param string $levelname The context level string introduced by the test writer
741 * @param string $contextref The context reference introduced by the test writer
742 * @return context
743 */
744 protected function get_context($levelname, $contextref) {
745 global $DB;
746
747 // Getting context levels and names (we will be using the English ones as it is the test site language).
748 $contextlevels = context_helper::get_all_levels();
749 $contextnames = array();
750 foreach ($contextlevels as $level => $classname) {
751 $contextnames[context_helper::get_level_name($level)] = $level;
752 }
753
754 if (empty($contextnames[$levelname])) {
755 throw new Exception('The specified "' . $levelname . '" context level does not exist');
756 }
757 $contextlevel = $contextnames[$levelname];
758
759 // Return it, we don't need to look for other internal ids.
760 if ($contextlevel == CONTEXT_SYSTEM) {
761 return context_system::instance();
762 }
763
764 switch ($contextlevel) {
765
766 case CONTEXT_USER:
767 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
768 break;
769
770 case CONTEXT_COURSECAT:
771 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
772 break;
773
774 case CONTEXT_COURSE:
775 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
776 break;
777
778 case CONTEXT_MODULE:
779 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
780 break;
781
782 default:
783 break;
784 }
785
786 $contextclass = $contextlevels[$contextlevel];
787 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
788 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
789 }
790
791 return $context;
792 }
793
f0200d14 794}