Skip to content

Commit

Permalink
MDL-82639 mod_quiz: Improve events for random questions
Browse files Browse the repository at this point in the history
This patch adds additional information to the existing
slot_created and slot_updated events (including specific
information for random slots) and adds a new event for
when a random slot has its filter condition updated.
  • Loading branch information
cameron1729 committed Aug 7, 2024
1 parent 8a6e856 commit e0977a3
Show file tree
Hide file tree
Showing 8 changed files with 269 additions and 74 deletions.
68 changes: 47 additions & 21 deletions mod/quiz/classes/event/slot_created.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@

namespace mod_quiz\event;

use core\exception\coding_exception;
use core\url;

/**
* The mod_quiz slot created event class.
*
Expand Down Expand Up @@ -51,39 +54,62 @@ public static function get_name() {
}

public function get_description() {
return "The user with id '$this->userid' created a new slot with id '{$this->objectid}' " .
"and slot number '{$this->other['slotnumber']}' " .
"on page '{$this->other['page']}' " .
"of the quiz with course module id '$this->contextinstanceid'.";

if (isset($this->other['questionbankentryid'])) {
$version = $this->other['version'] ?? 'Always latest';
return "The user with id '$this->userid' created a new slot with " .
"id '{$this->objectid}', " .
"slot number '{$this->other['slotnumber']}', and " .
"question bank entry id '{$this->other['questionbankentryid']}' (version '$version') " .
"on page '{$this->other['page']}' " .
"of the quiz with course module id '$this->contextinstanceid'.";
}

if (isset($this->other['questionscontextid'])) {
return "The user with id '$this->userid' created a new slot using question references with " .
"id '{$this->objectid}', " .
"slot number '{$this->other['slotnumber']}', " .
"question context '{$this->other['questionscontextid']}', and " .
"filter condition '{$this->other['filtercondition']}' " .
"on page '{$this->other['page']}' " .
"of the quiz with course module id '$this->contextinstanceid'.";
}
}

public function get_url() {
return new \moodle_url('/mod/quiz/edit.php', [
return new url('/mod/quiz/edit.php', [
'cmid' => $this->contextinstanceid
]);
}

protected function validate_data() {
parent::validate_data();
$missing = fn(string $field) => match($field) {
'version' => !array_key_exists('version', $this->other),
default => !isset($this->other[$field])
};

if (!isset($this->objectid)) {
throw new \coding_exception('The \'objectid\' value must be set.');
}

if (!isset($this->contextinstanceid)) {
throw new \coding_exception('The \'contextinstanceid\' value must be set.');
}
$any = fn(array $fields): bool => in_array(false, array_map($missing, $fields), true);
$all = fn(array $fields): bool => !in_array(true, array_map($missing, $fields), true);

if (!isset($this->other['quizid'])) {
throw new \coding_exception('The \'quizid\' value must be set in other.');
}
$missingmembers = array_filter(['objectid'], fn(string $member): bool => !isset($this->$member));
$missingfields = array_filter(['quizid', 'slotnumber', 'page'], $missing);
$mutexfields = [['questionbankentryid', 'version'], ['questionscontextid', 'filtercondition']];
$providedmutex = array_values(array_filter($mutexfields, $any));
$fieldsets = implode(", ", array_map(fn(array $fields): string => '(' . implode(', ', $fields) . ')', $mutexfields));
parent::validate_data();

if (!isset($this->other['slotnumber'])) {
throw new \coding_exception('The \'slotnumber\' value must be set in other.');
}
$errors = [
...array_map(fn(string $member): string => "The '$member' value must be set.", $missingmembers),
...array_map(fn(string $field): string => "The '$field' value must be set in other.", $missingfields),
...match(true) {
count($providedmutex) !== 1 => ["Values for exactly one of these field sets must be set in 'other': $fieldsets"],
!$all($providedmutex[0]) => ['The values: ' . implode(', ', $providedmutex[0]) . ' must all be set in \'other\'.'],
default => []
},
];

if (!isset($this->other['page'])) {
throw new \coding_exception('The \'page\' value must be set in other.');
if ($errors) {
throw new coding_exception("Errors in event data:\n\n" . implode("\n", $errors));
}
}

Expand Down
93 changes: 93 additions & 0 deletions mod/quiz/classes/event/slot_filtercondition_updated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

declare(strict_types=1);

namespace mod_quiz\event;

use core\event\base;
use core\exception\coding_exception;
use core\url;

/**
* This event is fired when the filter condition of a slot
* using the question set references table is updated.
*
* @package mod_quiz
* @copyright 2024 Catalyst IT Australia Pty Ltd
* @author Cameron Ball <[email protected]>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class slot_filtercondition_updated extends base {

#[\Override]
protected function init() {
$this->data['objecttable'] = 'quiz_slots';
$this->data['crud'] = 'c';
$this->data['edulevel'] = self::LEVEL_TEACHING;
}

#[\Override]
public static function get_name() {
return get_string('eventslotfilterconditionupdated', 'mod_quiz');
}

#[\Override]
public function get_description() {
return "The user with id '$this->userid' updated a slot using question references with " .
"id '{$this->objectid}' and" .
"slot number '{$this->other['slotnumber']}' " .
"on page '{$this->other['page']}' " .
"of the quiz with course module id '$this->contextinstanceid' " .
"to use quiestion context '{$this->other['questionscontextid']}' and " .
"filter condition '{$this->other['filtercondition']}'.";
}

#[\Override]
public function get_url() {
return new url('/mod/quiz/edit.php', ['cmid' => $this->contextinstanceid]);
}

#[\Override]
protected function validate_data() {
$missing = fn(string $field) => !isset($this->other[$field]);
$missingmembers = array_filter(['objectid'], fn(string $member): bool => !isset($this->$member));
$missingfields = array_filter(['quizid', 'slotnumber', 'page', 'questionscontextid', 'filtercondition'], $missing);
parent::validate_data();

$errors = [
...array_map(fn(string $member): string => "The '$member' value must be set.", $missingmembers),
...array_map(fn(string $field): string => "The '$field' value must be set in other.", $missingfields),
];

if ($errors) {
throw new coding_exception("Errors in event data:\n\n" . implode("\n", $errors));
}
}

#[\Override]
public static function get_objectid_mapping() {
return ['db' => 'quiz_slots', 'restore' => 'quiz_question_instance'];
}

#[\Override]
public static function get_other_mapping() {
$othermapped = [];
$othermapped['quizid'] = ['db' => 'quiz', 'restore' => 'quiz'];

return $othermapped;
}
}
48 changes: 17 additions & 31 deletions mod/quiz/classes/external/update_filter_condition.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
require_once($CFG->dirroot . '/question/editlib.php');
require_once($CFG->dirroot . '/mod/quiz/locallib.php');

use external_function_parameters;
use external_single_structure;
use external_value;
use external_api;
use core\context\module;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
use core_external\external_api;
use mod_quiz\quiz_settings;

/**
* Update the filter condition for a random question.
Expand Down Expand Up @@ -58,35 +60,19 @@ public static function execute_parameters(): external_function_parameters {
* @param string $filtercondition
* @return array result
*/
public static function execute(
int $cmid,
int $slotid,
string $filtercondition,
): array {
global $DB;
public static function execute(int $cmid, int $slotid, string $filtercondition): array {
['cmid' => $cmid, 'slotid' => $slotid, 'filtercondition' => $filtercondition] = self::validate_parameters(
self::execute_parameters(),
['cmid' => $cmid, 'slotid' => $slotid, 'filtercondition' => $filtercondition]
);

[
'cmid' => $cmid,
'slotid' => $slotid,
'filtercondition' => $filtercondition,
] = self::validate_parameters(self::execute_parameters(), [
'cmid' => $cmid,
'slotid' => $slotid,
'filtercondition' => $filtercondition,
]);

// Validate context.
$thiscontext = \context_module::instance($cmid);
self::validate_context($thiscontext);
require_capability('mod/quiz:manage', $thiscontext);
$context = module::instance($cmid);
self::validate_context($context);
require_capability('mod/quiz:manage', $context);

// Update filter condition.
$setparams = [
'itemid' => $slotid,
'questionarea' => 'slot',
'component' => 'mod_quiz',
];
$DB->set_field('question_set_references', 'filtercondition', $filtercondition, $setparams);
$filtercondition = json_decode($filtercondition, true);
$structure = quiz_settings::create_for_cmid($cmid)->get_structure();
$structure->update_random_question($slotid, $filtercondition);

return ['message' => get_string('updatefilterconditon_success', 'mod_quiz')];
}
Expand Down
49 changes: 42 additions & 7 deletions mod/quiz/classes/local/structure/slot_random.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
namespace mod_quiz\local\structure;

use context_module;
use core\context\module;
use core\exception\coding_exception;
use mod_quiz\event\slot_created;
use mod_quiz\event\slot_filtercondition_updated;

/**
* Class slot_random, represents a random question slot type.
Expand Down Expand Up @@ -214,19 +218,50 @@ public function insert($page) {
$this->referencerecord->filtercondition = $this->filtercondition;
$DB->insert_record('question_set_references', $this->referencerecord);

$trans->allow_commit();

// Log slot created event.
$cm = get_coursemodule_from_instance('quiz', $quiz->id);
$event = \mod_quiz\event\slot_created::create([
'context' => context_module::instance($cm->id),
slot_created::create([
'context' => module::instance($cm->id),
'objectid' => $this->record->id,
'other' => [
'quizid' => $quiz->id,
'slotnumber' => $this->record->slot,
'page' => $this->record->page
'page' => $this->record->page,
'questionscontextid' => $this->referencerecord->questionscontextid,
'filtercondition' => $this->referencerecord->filtercondition,
],
])->trigger();

$trans->allow_commit();
}

/**
* Update the filter condition for an existing random slot.
*
* @param array $filtercondition
*/
public function update_filtercondition(array $filtercondition): void {
global $DB;

if (!isset($this->record->id)) {
throw new coding_exception('Cannot update filtercondition without slot record ID.');
}

$cm = get_coursemodule_from_instance('quiz', $this->get_quiz()->id);
$transaction = $DB->start_delegated_transaction();
$params = ['component' => 'mod_quiz', 'questionarea' => 'slot', 'itemid' => $this->record->id];
$DB->set_field('question_set_references', 'filtercondition', json_encode($filtercondition), $params);
slot_filtercondition_updated::create([
'context' => module::instance($cm->id),
'objectid' => $this->record->id,
'other' => [
'quizid' => $this->get_quiz()->id,
'slotnumber' => $this->record->slot,
'page' => $this->record->page,
'questionscontextid' => $this->referencerecord->questionscontextid,
'filtercondition' => json_encode($filtercondition),
]
]);
$event->trigger();
])->trigger();
$transaction->allow_commit();
}
}
Loading

0 comments on commit e0977a3

Please sign in to comment.