MDL-71165 course: core_course_update_course external method

This commit is contained in:
Sara Arjona 2021-03-25 08:59:15 +01:00 committed by Andrew Nicols
parent a9b0f4dafe
commit 6347b916bc
12 changed files with 2052 additions and 1 deletions

View file

@ -0,0 +1,152 @@
<?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/>.
namespace core_course\external;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/externallib.php');
use external_api;
use external_function_parameters;
use external_value;
use external_multiple_structure;
use moodle_exception;
use coding_exception;
use context_course;
/**
* External secrvie to update the course from the course editor components.
*
* @package core_course
* @copyright 2021 Ferran Recio <moodle@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 4.0
*/
class update_course extends external_api {
/**
* Webservice parameters.
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters(
[
'action' => new external_value(
PARAM_ALPHANUMEXT,
'action: cm_hide, cm_show, section_hide, section_show, cm_moveleft...',
VALUE_REQUIRED
),
'courseid' => new external_value(PARAM_INT, 'course id', VALUE_REQUIRED),
'ids' => new external_multiple_structure(
new external_value(PARAM_INT, 'Target id'),
'Affected ids',
VALUE_DEFAULT,
[]
),
'targetsectionid' => new external_value(
PARAM_INT, 'Optional target section id', VALUE_DEFAULT, null
),
'targetcmid' => new external_value(
PARAM_INT, 'Optional target cm id', VALUE_DEFAULT, null
),
]
);
}
/**
* This webservice will execute any action from the course editor. The default actions
* are located in core_course\stateactions but the format plugin can extend that class
* in format_XXX\course.
*
* The specific action methods will register in a core_course\stateupdates all the affected
* sections, cms and course attribute. This object (in JSON) will be send back to the
* frontend editor to refresh the updated state elements.
*
* By default, core_course\stateupdates will register only create, delete and update events
* on cms, sections and the general course data. However, if some plugin needs adhoc messages for
* its own mutation module, it extend this class in format_XXX\course.
*
* @param string $action the action name to execute
* @param int $courseid the course id
* @param int[] $ids the affected ids (section or cm depending on the action)
* @param int $targetsectionid optional target section id (for move action)
* @param int $targetcmid optional target cm id (for move action)
* @return string Course state in JSON
*/
public static function execute(string $action, int $courseid, array $ids = [],
?int $targetsectionid = null, ?int $targetcmid = null): string {
global $CFG;
require_once($CFG->dirroot . '/course/lib.php');
$params = external_api::validate_parameters(self::execute_parameters(), [
'action' => $action,
'courseid' => $courseid,
'ids' => $ids,
'targetsectionid' => $targetsectionid,
'targetcmid' => $targetcmid,
]);
$action = $params['action'];
$courseid = $params['courseid'];
$ids = $params['ids'];
$targetsectionid = $params['targetsectionid'];
$targetcmid = $params['targetcmid'];
self::validate_context(context_course::instance($courseid));
$courseformat = course_get_format($courseid);
// Create a course changes tracker object.
$defaultupdatesclass = 'core_course\\stateupdates';
$updatesclass = 'format_' . $courseformat->get_format() . '\\stateupdates';
if (!class_exists($updatesclass)) {
$updatesclass = $defaultupdatesclass;
}
$updates = new $updatesclass($courseformat);
if (!is_a($updates, $defaultupdatesclass)) {
throw new coding_exception("The \"$updatesclass\" class must extend \"$defaultupdatesclass\"");
}
// Get the actions class from the course format.
$actionsclass = 'format_'. $courseformat->get_format().'\\stateactions';
if (!class_exists($actionsclass)) {
$actionsclass = 'core_course\\stateactions';
}
$actions = new $actionsclass();
if (!is_callable([$actions, $action])) {
throw new moodle_exception("Invalid course state action $action in ".get_class($actions));
}
// Execute the action.
$actions->$action($updates, $courseformat->get_course(), $ids, $targetsectionid, $targetcmid);
return json_encode($updates);
}
/**
* Webservice returns.
*
* @return external_value
*/
public static function execute_returns(): external_value {
return new external_value(PARAM_RAW, 'Encoded course update JSON');
}
}

View file

@ -0,0 +1,237 @@
<?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/>.
namespace core_course;
use core_course\stateupdates;
use stdClass;
use course_modinfo;
use moodle_exception;
/**
* Contains the core course state actions.
*
* The methods from this class should be executed via "core_course_edit" web service.
*
* Each format plugin could extend this class to provide new actions to the editor.
* Extended classes should be locate in "format_XXX\course" namespace and
* extends core_course\stateactions.
*
* @package core_course
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class stateactions {
/**
* Add the update messages of the updated version of any cm and section related to the cm ids.
*
* This action is mainly used by legacy actions to partially update the course state when the
* result of core_course_edit_module is not enough to generate the correct state data.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course module ids
* @param int $targetsectionid optional target section id
* @param int $targetcmid optional target cm id
*/
public function cm_state(
stateupdates $updates,
stdClass $course,
array $ids,
?int $targetsectionid = null,
?int $targetcmid = null
): void {
// Collect all section and cm to return.
$cmids = [];
foreach ($ids as $cmid) {
$cmids[$cmid] = true;
}
if ($targetcmid) {
$cmids[$targetcmid] = true;
}
$sectionids = [];
if ($targetsectionid) {
$this->validate_sections($course, [$targetsectionid], __FUNCTION__);
$sectionids[$targetsectionid] = true;
}
$this->validate_cms($course, array_keys($cmids), __FUNCTION__);
$modinfo = course_modinfo::instance($course);
foreach (array_keys($cmids) as $cmid) {
// Add this action to updates array.
$updates->add_cm_update($cmid);
$cm = $modinfo->get_cm($cmid);
$sectionids[$cm->section] = true;
}
foreach (array_keys($sectionids) as $sectionid) {
$updates->add_section_update($sectionid);
}
}
/**
* Add the update messages of the updated version of any cm and section related to the section ids.
*
* This action is mainly used by legacy actions to partially update the course state when the
* result of core_course_edit_module is not enough to generate the correct state data.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course section ids
* @param int $targetsectionid optional target section id
* @param int $targetcmid optional target cm id
*/
public function section_state(
stateupdates $updates,
stdClass $course,
array $ids,
?int $targetsectionid = null,
?int $targetcmid = null
): void {
$cmids = [];
if ($targetcmid) {
$this->validate_cms($course, [$targetcmid], __FUNCTION__);
$cmids[$targetcmid] = true;
}
$sectionids = [];
foreach ($ids as $sectionid) {
$sectionids[$sectionid] = true;
}
if ($targetsectionid) {
$sectionids[$targetsectionid] = true;
}
$this->validate_sections($course, array_keys($sectionids), __FUNCTION__);
$modinfo = course_modinfo::instance($course);
foreach (array_keys($sectionids) as $sectionid) {
$sectioninfo = $modinfo->get_section_info_by_id($sectionid);
$updates->add_section_update($sectionid);
// Add cms.
if (empty($modinfo->sections[$sectioninfo->section])) {
continue;
}
foreach ($modinfo->sections[$sectioninfo->section] as $modnumber) {
$mod = $modinfo->cms[$modnumber];
if ($mod->is_visible_on_course_page()) {
$cmids[$mod->id] = true;
}
}
}
foreach (array_keys($cmids) as $cmid) {
// Add this action to updates array.
$updates->add_cm_update($cmid);
}
}
/**
* Add all the update messages from the complete course state.
*
* This action is mainly used by legacy actions to partially update the course state when the
* result of core_course_edit_module is not enough to generate the correct state data.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course module ids (not used)
* @param int $targetsectionid optional target section id (not used)
* @param int $targetcmid optional target cm id (not used)
*/
public function course_state(
stateupdates $updates,
stdClass $course,
array $ids = [],
?int $targetsectionid = null,
?int $targetcmid = null
): void {
$modinfo = course_modinfo::instance($course);
$updates->add_course_update();
// Add sections updates.
$sections = $modinfo->get_section_info_all();
$sectionids = [];
foreach ($sections as $sectioninfo) {
$sectionids[] = $sectioninfo->id;
}
if (!empty($sectionids)) {
$this->section_state($updates, $course, $sectionids);
}
}
/**
* Checks related to sections: course format support them, all given sections exist and topic 0 is not included.
*
* @param stdClass $course The course where given $sectionids belong.
* @param array $sectionids List of sections to validate.
* @param string|null $info additional information in case of error (default null).
* @throws moodle_exception if any id is not valid
*/
protected function validate_sections(stdClass $course, array $sectionids, ?string $info = null): void {
global $DB;
if (empty($sectionids)) {
throw new moodle_exception('emptysectionids', 'core', null, $info);
}
// No section actions are allowed if course format does not support sections.
$courseformat = course_get_format($course->id);
if (!$courseformat->uses_sections()) {
throw new moodle_exception('sectionactionnotsupported', 'core', null, $info);
}
list($insql, $inparams) = $DB->get_in_or_equal($sectionids, SQL_PARAMS_NAMED);
// Check if all the given sections exist.
$couintsections = $DB->count_records_select('course_sections', "id $insql", $inparams);
if ($couintsections != count($sectionids)) {
throw new moodle_exception('unexistingsectionid', 'core', null, $info);
}
}
/**
* Checks related to course modules: all given cm exist.
*
* @param stdClass $course The course where given $cmids belong.
* @param array $cmids List of course module ids to validate.
* @param string $info additional information in case of error.
* @throws moodle_exception if any id is not valid
*/
protected function validate_cms(stdClass $course, array $cmids, ?string $info = null): void {
if (empty($cmids)) {
throw new moodle_exception('emptycmids', 'core', null, $info);
}
$moduleinfo = get_fast_modinfo($course->id);
$intersect = array_intersect($cmids, array_keys($moduleinfo->get_cms()));
if (count($cmids) != count($intersect)) {
throw new moodle_exception('unexistingcmid', 'core', null, $info);
}
}
}

View file

@ -0,0 +1,200 @@
<?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/>.
namespace core_course;
use coding_exception;
use core_course\course_format;
use renderer_base;
use stdClass;
use course_modinfo;
use JsonSerializable;
/**
* Class to track state actions.
*
* The methods from this class should be executed via "stateactions" methods.
*
* Each format plugin could extend this class to provide new updates to the frontend
* mutation module.
* Extended classes should be locate in "format_XXX\course" namespace and
* extends core_course\stateupdates.
*
* @package core_course
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class stateupdates implements JsonSerializable {
/** @var course_format format the course format */
protected $format;
/** @var renderer_base renderer format renderer */
protected $output;
/** @var array the tracked updates */
protected $updates;
/**
* State update class constructor.
*
* @param course_format $format Course format.
*/
public function __construct(course_format $format) {
global $PAGE;
$this->format = $format;
$this->output = $this->format->get_renderer($PAGE);
$this->updates = [];
}
/**
* Return the data to serialize the current track in JSON.
*
* @return stdClass the statement data structure
*/
public function jsonSerialize(): array {
return $this->updates;
}
/**
* Add track about a general course state change.
*/
public function add_course_update(): void {
$courseclass = $this->format->get_output_classname('course_format\state');
$currentstate = new $courseclass($this->format);
$this->add_update('course', 'update', $currentstate->export_for_template($this->output));
}
/**
* Add track about a section state update.
*
* @param int $sectionid The affected section id.
*/
public function add_section_update(int $sectionid): void {
$this->create_or_update_section($sectionid, 'update');
}
/**
* Add track about a new section created.
*
* @param int $sectionid The affected section id.
*/
public function add_section_create(int $sectionid): void {
$this->create_or_update_section($sectionid, 'create');
}
/**
* Add track about section created or updated.
*
* @param int $sectionid The affected section id.
* @param string $action The action to track for the section ('create' or 'update).
*/
protected function create_or_update_section(int $sectionid, string $action): void {
if ($action != 'create' && $action != 'update') {
throw new coding_exception(
"Invalid action passed ($action) to create_or_update_section. Only 'create' and 'update' are valid."
);
}
$course = $this->format->get_course();
$modinfo = course_modinfo::instance($course);
$section = $modinfo->get_section_info_by_id($sectionid, MUST_EXIST);
if (!$section->uservisible) {
return;
}
$sectionclass = $this->format->get_output_classname('section_format\state');
$currentstate = new $sectionclass($this->format, $section);
$this->add_update('section', $action, $currentstate->export_for_template($this->output));
}
/**
* Add track about a section deleted.
*
* @param int $sectionid The affected section id.
*/
public function add_section_delete(int $sectionid): void {
$this->add_update('section', 'delete', (object)['id' => $sectionid]);
}
/**
* Add track about a course module state update.
*
* @param int $cmid the affected course module id
*/
public function add_cm_update(int $cmid): void {
$this->create_or_update_cm($cmid, 'update');
}
/**
* Add track about a course module created.
*
* @param int $cmid the affected course module id
*/
public function add_cm_create(int $cmid): void {
$this->create_or_update_cm($cmid, 'create', true);
}
/**
* Add track about section created or updated.
*
* @param int $cmid The affected course module id.
* @param string $action The action to track for the section ('create' or 'update').
*/
protected function create_or_update_cm(int $cmid, string $action): void {
$modinfo = course_modinfo::instance($this->format->get_course());
$cm = $modinfo->get_cm($cmid);
$section = $modinfo->get_section_info_by_id($cm->section);
if (!$section->uservisible || !$cm->is_visible_on_course_page()) {
return;
}
$cmclass = $this->format->get_output_classname('cm_format\state');
$currentstate = new $cmclass($this->format, $section, $cm);
$this->add_update('cm', $action, $currentstate->export_for_template($this->output));
}
/**
* Add track about a course module deleted.
*
* @param int $cmid the affected course module id
*/
public function add_cm_delete(int $cmid): void {
$this->add_update('cm', 'delete', (object)['id' => $cmid]);
}
/**
* Add a valid update message to the update list.
*
* @param string $name: the update name
* @param string $action: the update action (usually update, create, delete)
* @param stdClass $fields: the object fields
*/
protected function add_update(string $name, string $action, stdClass $fields): void {
$this->updates[] = (object)[
'name' => $name,
'action' => $action,
'fields' => $fields,
];
}
}

View file

@ -0,0 +1,236 @@
<?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/>.
namespace core_course\external;
use stdClass;
use moodle_exception;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* Tests for the update_course class.
*
* @package core_course
* @category test
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core_course\external\update_course
*/
class update_course_test extends \externallib_advanced_testcase {
/**
* Setup to ensure that fixtures are loaded.
*/
public static function setupBeforeClass(): void {
global $CFG;
require_once($CFG->dirroot . '/course/tests/fixtures/format_theunittest.php');
require_once($CFG->dirroot . '/course/tests/fixtures/format_theunittest_output_course_format_state.php');
require_once($CFG->dirroot . '/course/tests/fixtures/format_theunittest_stateactions.php');
}
/**
* Test the webservice can execute a core state action (cm_state).
*
* @dataProvider execute_course_state_provider
* @covers ::execute
*
* @param string $format the course format
* @param string $action the state action name
* @param array $expected the expected results
* @param bool $expectexception if an exception should happen.
* @param bool $assertdebug if an debug message should happen.
*/
public function test_execute_course_state(
string $format,
string $action,
array $expected,
bool $expectexception,
bool $assertdebug
) {
$this->resetAfterTest();
// Create a course with two activities.
$course = $this->getDataGenerator()->create_course(['format' => $format]);
$activity = $this->getDataGenerator()->create_module('book', ['course' => $course->id]);
$this->setAdminUser();
// Expect exception.
if ($expectexception) {
$this->expectException(moodle_exception::class);
}
// Execute course action.
$results = json_decode(update_course::execute($action, $course->id, [$activity->cmid]));
if ($assertdebug) {
// Some course formats hasn't the renderer file, so a debugging message will be displayed.
$this->assertDebuggingCalled();
}
// Check result.
$this->assertCount($expected['count'], $results);
$update = $this->find_update($results, $expected['action'], 'cm', $activity->cmid);
$this->assertNotEmpty($update);
if ($expected['visible'] === null) {
$this->assertObjectNotHasAttribute('visible', $update->fields);
} else {
$this->assertEquals($expected['visible'], $update->fields->visible);
}
}
/**
* Data provider for test_execute_course_state
*
* @return array of testing scenarios
*/
public function execute_course_state_provider(): array {
return [
'Execute a core state action (cm_state)' => [
'format' => 'topics',
'action' => 'cm_state',
'expected' => [
'count' => 2,
'action' => 'update',
'visible' => 1,
],
'expectexception' => false,
'assertdebug' => false,
],
'Formats can override core state actions' => [
'format' => 'theunittest',
'action' => 'cm_state',
'expected' => [
'count' => 1,
'action' => 'create',
'visible' => 1,
],
'expectexception' => false,
'assertdebug' => true,
],
'Formats can create new state actions' => [
'format' => 'theunittest',
'action' => 'format_do_something',
'expected' => [
'count' => 1,
'action' => 'delete',
'visible' => null,
],
'expectexception' => false,
'assertdebug' => true,
],
'Innexisting state action' => [
'format' => 'topics',
'action' => 'Wrong_State_Action_Name',
'expected' => [],
'expectexception' => true,
'assertdebug' => false,
],
];
}
/**
* Helper methods to find a specific update in the updadelist.
*
* @param array $updatelist the update list
* @param string $action the action to find
* @param string $name the element name to find
* @param int $identifier the element id value
* @return stdClass|null the object found, if any.
*/
private function find_update(
array $updatelist,
string $action,
string $name,
int $identifier
): ?stdClass {
foreach ($updatelist as $update) {
if ($update->action != $action || $update->name != $name) {
continue;
}
if (!isset($update->fields->id)) {
continue;
}
if ($update->fields->id == $identifier) {
return $update;
}
}
return null;
}
/**
* Test a wrong course id.
*
* @covers ::execute
*
*/
public function test_execute_wrong_courseid() {
$this->resetAfterTest();
// Create a course with two activities.
$course = $this->getDataGenerator()->create_course(['format' => 'topics']);
$activity = $this->getDataGenerator()->create_module('book', ['course' => $course->id]);
$this->setAdminUser();
// Expect exception.
$this->expectException(moodle_exception::class);
// Execute course action.
$results = json_decode(update_course::execute('cm_state', $course->id + 1, [$activity->cmid]));
}
/**
* Test target params are passed to the state actions.
*
* @covers ::execute
*/
public function test_execute_target_params() {
$this->resetAfterTest();
// Create a course with two activities.
$course = $this->getDataGenerator()->create_course(['format' => 'theunittest', 'numsections' => 2]);
$activity = $this->getDataGenerator()->create_module('book', ['course' => $course->id]);
$modinfo = get_fast_modinfo($course);
$section = $modinfo->get_section_info(1);
$this->setAdminUser();
// Execute action with targetsectionid.
$results = json_decode(update_course::execute('targetsection_test', $course->id, [], $section->id));
$this->assertDebuggingCalled();
$this->assertCount(1, $results);
$update = $this->find_update($results, 'update', 'section', $section->id);
$this->assertNotEmpty($update);
// Execute action with targetcmid.
$results = json_decode(update_course::execute('targetcm_test', $course->id, [], null, $activity->cmid));
$this->assertDebuggingCalled();
$this->assertCount(1, $results);
$update = $this->find_update($results, 'update', 'cm', $activity->cmid);
$this->assertNotEmpty($update);
}
}

View file

@ -0,0 +1,111 @@
<?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/>.
namespace format_theunittest;
use core_course\stateupdates;
use core_course\stateactions as core_actions;
use stdClass;
/**
* Fixture for fake course stateactions testing.
*
* @package core_course
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class stateactions extends core_actions {
/**
* Alternative cm_state state action for testing.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course module ids
* @param int $targetsectionid optional target section id
* @param int $targetcmid optional target cm id
*/
public function cm_state(
stateupdates $updates,
stdClass $course,
array $ids,
?int $targetsectionid = null,
?int $targetcmid = null
): void {
$updates->add_cm_create(array_pop($ids));
}
/**
* Course format custom state action.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course module ids
* @param int $targetsectionid optional target section id
* @param int $targetcmid optional target cm id
*/
public function format_do_something(
stateupdates $updates,
stdClass $course,
array $ids,
?int $targetsectionid = null,
?int $targetcmid = null
): void {
$updates->add_cm_delete(array_pop($ids));
}
/**
* Course format target section testing action.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course module ids
* @param int $targetsectionid optional target section id
* @param int $targetcmid optional target cm id
*/
public function targetsection_test(
stateupdates $updates,
stdClass $course,
array $ids,
?int $targetsectionid = null,
?int $targetcmid = null
): void {
$updates->add_section_update($targetsectionid);
}
/**
* Course format target cm testing action.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the list of affected course module ids
* @param int $targetsectionid optional target section id
* @param int $targetcmid optional target cm id
*/
public function targetcm_test(
stateupdates $updates,
stdClass $course,
array $ids,
?int $targetsectionid = null,
?int $targetcmid = null
): void {
$updates->add_cm_update($targetcmid);
}
}

View file

@ -0,0 +1,608 @@
<?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/>.
namespace core_course;
use moodle_exception;
use stdClass;
/**
* Tests for the stateactions class.
*
* @package core_course
* @category test
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core_course\stateactions
*/
class stateactions_test extends \advanced_testcase {
/**
* Helper method to create an activity into a section and add it to the $sections and $activities arrays.
*
* @param int $courseid Course identifier where the activity will be added.
* @param string $type Activity type ('forum', 'assign', ...).
* @param int $section Section number where the activity will be added.
* @param bool $visible Whether the activity will be visible or not.
* @return int the activity cm id
*/
private function create_activity(
int $courseid,
string $type,
int $section,
bool $visible = true
): int {
$activity = $this->getDataGenerator()->create_module(
$type,
['course' => $courseid],
[
'section' => $section,
'visible' => $visible
]
);
return $activity->cmid;
}
/**
* Helper to create a course and generate a section list.
*
* @param string $format the course format
* @param int $sections the number of sections
* @param int[] $hiddensections the section numbers to hide
* @return stdClass the course object
*/
private function create_course(string $format, int $sections, array $hiddensections): stdClass {
global $DB;
$course = $this->getDataGenerator()->create_course(['numsections' => $sections, 'format' => $format]);
foreach ($hiddensections as $section) {
set_section_visible($course->id, $section, 0);
}
return $course;
}
/**
* Return an array if the course references.
*
* This method is used to create alias to sections and other stuff in the dataProviders.
*
* @param stdClass $course the course object
* @return int[] a relation betwee all references and its element id
*/
private function course_references(stdClass $course): array {
global $DB;
$references = [];
$sectionrecords = $DB->get_records('course_sections', ['course' => $course->id]);
foreach ($sectionrecords as $id => $section) {
$references["section{$section->section}"] = $section->id;
}
$references['course'] = $course->id;
$references['invalidsection'] = -1;
$references['invalidcm'] = -1;
return $references;
}
/**
* Translate a references array into current ids.
*
* @param string[] $references the references list
* @param string[] $values the values to translate
* @return int[] the list of ids
*/
private function translate_references(array $references, array $values): array {
$result = [];
foreach ($values as $value) {
$result[] = $references[$value];
}
return $result;
}
/**
* Generate a sorted and summarized list of an state updates message.
*
* It is important to note that the order in the update messages are not important in a real scenario
* because each message affects a specific part of the course state. However, for the PHPUnit test
* have them sorted and classified simplifies the asserts.
*
* @param stateupdates $updateobj the state updates object
* @return array of all data updates.
*/
private function summarize_updates(stateupdates $updateobj): array {
// Check state returned after executing given action.
$updatelist = $updateobj->jsonSerialize();
// Initial summary structure.
$result = [
'create' => [
'course' => [],
'section' => [],
'cm' => [],
'count' => 0,
],
'update' => [
'course' => [],
'section' => [],
'cm' => [],
'count' => 0,
],
'delete' => [
'course' => [],
'section' => [],
'cm' => [],
'count' => 0,
],
];
foreach ($updatelist as $update) {
if (!isset($result[$update->action])) {
$result[$update->action] = [
'course' => [],
'section' => [],
'cm' => [],
'count' => 0,
];
}
$elementid = $update->fields->id ?? 0;
$result[$update->action][$update->name][$elementid] = $update->fields;
$result[$update->action]['count']++;
}
return $result;
}
/**
* Test the behaviour course_state.
*
* @dataProvider get_state_provider
* @covers ::course_state
* @covers ::section_state
* @covers ::cm_state
*
* @param string $format The course will be created with this course format.
* @param string $role The role of the user that will execute the method.
* @param string $method the method to call
* @param array $params the ids, targetsection and targetcm to use as params
* @param array $expectedresults List of the course module names expected after calling the method.
* @param bool $expectedexception If this call will raise an exception.
* @param bool $assertdebug If this call will get some debug message.
*/
public function test_get_state(
string $format,
string $role,
string $method,
array $params,
array $expectedresults,
bool $expectedexception = false,
bool $assertdebug = false
): void {
$this->resetAfterTest();
// Create a course with 3 sections, 1 of them hidden.
$course = $this->create_course($format, 3, [2]);
$references = $this->course_references($course);
// Create and enrol user using given role.
if ($role == 'admin') {
$this->setAdminUser();
} else {
$user = $this->getDataGenerator()->create_user();
if ($role != 'unenroled') {
$this->getDataGenerator()->enrol_user($user->id, $course->id, $role);
}
$this->setUser($user);
}
// Add some activities to the course. One visible and one hidden in both sections 1 and 2.
$references["cm0"] = $this->create_activity($course->id, 'assign', 1, true);
$references["cm1"] = $this->create_activity($course->id, 'book', 1, false);
$references["cm2"] = $this->create_activity($course->id, 'glossary', 2, true);
$references["cm3"] = $this->create_activity($course->id, 'page', 2, false);
if ($expectedexception) {
$this->expectException(moodle_exception::class);
}
// Initialise stateupdates.
$courseformat = course_get_format($course->id);
$updates = new stateupdates($courseformat);
if ($assertdebug) {
// Some course formats hasn't the renderer file, so a debugging message will be displayed.
$this->assertDebuggingCalled();
}
// Execute given method.
$actions = new stateactions();
$actions->$method(
$updates,
$course,
$this->translate_references($references, $params['ids']),
$references[$params['targetsectionid']] ?? null,
$references[$params['targetcmid']] ?? null
);
// Format results in a way we can compare easily.
$results = $this->summarize_updates($updates);
// The state actions does not use create or delete actions because they are designed
// to refresh parts of the state.
$this->assertEquals(0, $results['create']['count']);
$this->assertEquals(0, $results['delete']['count']);
// Validate we have all the expected entries.
$expectedtotal = count($expectedresults['course']) + count($expectedresults['section']) + count($expectedresults['cm']);
$this->assertEquals($expectedtotal, $results['update']['count']);
// Validate course, section and cm.
foreach ($expectedresults as $name => $referencekeys) {
foreach ($referencekeys as $referencekey) {
$this->assertArrayHasKey($references[$referencekey], $results['update'][$name]);
}
}
}
/**
* Data provider for data request creation tests.
*
* @return array the testing scenarios
*/
public function get_state_provider(): array {
return array_merge(
$this->course_state_provider('weeks'),
$this->course_state_provider('topics'),
$this->course_state_provider('social'),
$this->section_state_provider('weeks', 'admin'),
$this->section_state_provider('weeks', 'editingteacher'),
$this->section_state_provider('weeks', 'student'),
$this->section_state_provider('topics', 'admin'),
$this->section_state_provider('topics', 'editingteacher'),
$this->section_state_provider('topics', 'student'),
$this->section_state_provider('social', 'admin'),
$this->section_state_provider('social', 'editingteacher'),
$this->section_state_provider('social', 'student'),
$this->cm_state_provider('weeks', 'admin'),
$this->cm_state_provider('weeks', 'editingteacher'),
$this->cm_state_provider('weeks', 'student'),
$this->cm_state_provider('topics', 'admin'),
$this->cm_state_provider('topics', 'editingteacher'),
$this->cm_state_provider('topics', 'student'),
$this->cm_state_provider('social', 'admin'),
$this->cm_state_provider('social', 'editingteacher'),
$this->cm_state_provider('social', 'student'),
);
}
/**
* Course state data provider.
*
* @param string $format the course format
* @return array the testing scenarios
*/
public function course_state_provider(string $format): array {
$expectedexception = ($format === 'social');
return [
// Tests for course_state.
"admin $format course_state" => [
'format' => $format,
'role' => 'admin',
'method' => 'course_state',
'params' => [
'ids' => [], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => ['course'],
'section' => ['section0', 'section1', 'section2', 'section3'],
'cm' => ['cm0', 'cm1', 'cm2', 'cm3'],
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"editingteacher $format course_state" => [
'format' => $format,
'role' => 'editingteacher',
'method' => 'course_state',
'params' => [
'ids' => [], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => ['course'],
'section' => ['section0', 'section1', 'section2', 'section3'],
'cm' => ['cm0', 'cm1', 'cm2', 'cm3'],
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"student $format course_state" => [
'format' => $format,
'role' => 'student',
'method' => 'course_state',
'params' => [
'ids' => [], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => ['course'],
'section' => ['section0', 'section1', 'section3'],
'cm' => ['cm0'],
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
];
}
/**
* Section state data provider.
*
* @param string $format the course format
* @param string $role the user role
* @return array the testing scenarios
*/
public function section_state_provider(string $format, string $role): array {
// Social format will raise an exception and debug messages because it does not
// use sections and it does not provide a renderer.
$expectedexception = ($format === 'social');
// All sections and cms that the user can access to.
$usersections = ['section0', 'section1', 'section2', 'section3'];
$usercms = ['cm0', 'cm1', 'cm2', 'cm3'];
if ($role == 'student') {
$usersections = ['section0', 'section1', 'section3'];
$usercms = ['cm0'];
}
return [
"$role $format section_state no section" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => [], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [],
'expectedexception' => true,
'assertdebug' => $expectedexception,
],
"$role $format section_state section 0" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['section0'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section0'], $usersections),
'cm' => [],
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"$role $format section_state visible section" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['section1'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1'], $usersections),
'cm' => array_intersect(['cm0', 'cm1'], $usercms),
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"$role $format section_state hidden section" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['section2'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section2'], $usersections),
'cm' => array_intersect(['cm2', 'cm3'], $usercms),
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"$role $format section_state several sections" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['section1', 'section3'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1', 'section3'], $usersections),
'cm' => array_intersect(['cm0', 'cm1'], $usercms),
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"$role $format section_state invalid section" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['invalidsection'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [],
'expectedexception' => true,
'assertdebug' => $expectedexception,
],
"$role $format section_state using target section" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['section1'], 'targetsectionid' => 'section3', 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1', 'section3'], $usersections),
'cm' => array_intersect(['cm0', 'cm1'], $usercms),
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
"$role $format section_state using target targetcmid" => [
'format' => $format,
'role' => $role,
'method' => 'section_state',
'params' => [
'ids' => ['section3'], 'targetsectionid' => null, 'targetcmid' => 'cm1'
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section3'], $usersections),
'cm' => array_intersect(['cm1'], $usercms),
],
'expectedexception' => $expectedexception,
'assertdebug' => $expectedexception,
],
];
}
/**
* Course module state data provider.
*
* @param string $format the course format
* @param string $role the user role
* @return array the testing scenarios
*/
public function cm_state_provider(string $format, string $role): array {
// Social format will raise debug messages because it does not provide a renderer.
$assertdebug = ($format === 'social');
// All sections and cms that the user can access to.
$usersections = ['section0', 'section1', 'section2', 'section3'];
$usercms = ['cm0', 'cm1', 'cm2', 'cm3'];
if ($role == 'student') {
$usersections = ['section0', 'section1', 'section3'];
$usercms = ['cm0'];
}
return [
"$role $format cm_state no cms" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => [], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [],
'expectedexception' => true,
'assertdebug' => $assertdebug,
],
"$role $format cm_state visible cm" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => ['cm0'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1'], $usersections),
'cm' => array_intersect(['cm0'], $usercms),
],
'expectedexception' => false,
'assertdebug' => $assertdebug,
],
"$role $format cm_state hidden cm" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => ['cm1'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1'], $usersections),
'cm' => array_intersect(['cm1'], $usercms),
],
'expectedexception' => false,
'assertdebug' => $assertdebug,
],
"$role $format cm_state several cm" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => ['cm0', 'cm2'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1', 'section2'], $usersections),
'cm' => array_intersect(['cm0', 'cm2'], $usercms),
],
'expectedexception' => false,
'assertdebug' => $assertdebug,
],
"$role $format cm_state using targetsection" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => ['cm0'], 'targetsectionid' => 'section2', 'targetcmid' => null
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1', 'section2'], $usersections),
'cm' => array_intersect(['cm0'], $usercms),
],
'expectedexception' => ($format === 'social'),
'assertdebug' => $assertdebug,
],
"$role $format cm_state using targetcm" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => ['cm0'], 'targetsectionid' => null, 'targetcmid' => 'cm3'
],
'expectedresults' => [
'course' => [],
'section' => array_intersect(['section1', 'section2'], $usersections),
'cm' => array_intersect(['cm0', 'cm3'], $usercms),
],
'expectedexception' => false,
'assertdebug' => $assertdebug,
],
"$role $format cm_state using an invalid cm" => [
'format' => $format,
'role' => $role,
'method' => 'cm_state',
'params' => [
'ids' => ['invalidcm'], 'targetsectionid' => null, 'targetcmid' => null
],
'expectedresults' => [],
'expectedexception' => true,
'assertdebug' => $assertdebug,
],
];
}
}

View file

@ -0,0 +1,386 @@
<?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/>.
namespace core_course;
use stdClass;
/**
* Tests for the stateactions class.
*
* @package core_course
* @category test
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core_course\stateactions
*/
class stateupdates_test extends \advanced_testcase {
/**
* Test for add_course_update.
*
* @dataProvider add_course_update_provider
* @covers ::add_course_update
*
* @param string $role the user role in the course
*/
public function test_add_course_update(string $role): void {
global $PAGE;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course(['format' => 'topics']);
// Create and enrol user using given role.
if ($role == 'admin') {
$this->setAdminUser();
} else {
$user = $this->getDataGenerator()->create_user();
if ($role != 'unenroled') {
$this->getDataGenerator()->enrol_user($user->id, $course->id, $role);
}
$this->setUser($user);
}
// Initialise stateupdates.
$format = course_get_format($course);
$updates = new stateupdates($format);
// Get the expected export.
$renderer = $format->get_renderer($PAGE);
$stateclass = $format->get_output_classname("course_format\state");
$currentstate = new $stateclass($format);
$expected = $currentstate->export_for_template($renderer);
$updates->add_course_update();
$updatelist = $updates->jsonSerialize();
$this->assertCount(1, $updatelist);
$update = array_pop($updatelist);
$this->assertEquals('update', $update->action);
$this->assertEquals('course', $update->name);
$this->assertEquals($expected, $update->fields);
}
/**
* Data provider for test_add_course_update.
*
* @return array testing scenarios
*/
public function add_course_update_provider() {
return [
'Admin role' => [
'admin',
],
'Teacher role' => [
'editingteacher',
],
'Student role' => [
'student',
],
];
}
/**
* Helper methods to find a specific update in the updadelist.
*
* @param array $updatelist the update list
* @param string $action the action to find
* @param string $name the element name to find
* @param int $identifier the element id value
* @return stdClass|null the object found, if any.
*/
private function find_update(
array $updatelist,
string $action,
string $name,
int $identifier
): ?stdClass {
foreach ($updatelist as $update) {
if ($update->action != $action || $update->name != $name) {
continue;
}
if (!isset($update->fields->id)) {
continue;
}
if ($update->fields->id == $identifier) {
return $update;
}
}
return null;
}
/**
* Add track about a section state update.
*
* @dataProvider add_section_provider
* @covers ::add_course_update
* @covers ::add_course_create
* @covers ::add_course_delete
*
* @param string $action the action name
* @param string $role the user role name
* @param array $expected the expected results
*/
public function test_add_section(string $action, string $role, array $expected): void {
global $PAGE, $DB;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course(['numsections' => 2, 'format' => 'topics']);
// Set section 2 hidden.
set_section_visible($course->id, 2, 0);
// Create and enrol user using given role.
if ($role == 'admin') {
$this->setAdminUser();
} else {
$user = $this->getDataGenerator()->create_user();
if ($role != 'unenroled') {
$this->getDataGenerator()->enrol_user($user->id, $course->id, $role);
}
$this->setUser($user);
}
// Initialise stateupdates.
$format = course_get_format($course);
$updates = new stateupdates($format);
$modinfo = $format->get_modinfo();
// Get the expected export.
$renderer = $format->get_renderer($PAGE);
$stateclass = $format->get_output_classname("section_format\state");
// Execute method for both sections.
$method = "add_section_{$action}";
$sections = $modinfo->get_section_info_all();
foreach ($sections as $section) {
$updates->$method($section->id);
}
$updatelist = $updates->jsonSerialize();
$this->assertCount(count($expected), $updatelist);
foreach ($expected as $sectionnum) {
$section = $sections[$sectionnum];
$currentstate = new $stateclass($format, $section);
$expected = $currentstate->export_for_template($renderer);
$update = $this->find_update($updatelist, $action, 'section', $section->id);
$this->assertEquals($action, $update->action);
$this->assertEquals('section', $update->name);
// Delete does not provide all fields.
if ($action == 'delete') {
$this->assertEquals($section->id, $update->fields->id);
} else {
$this->assertEquals($expected, $update->fields);
}
}
}
/**
* Data provider for test_add_section.
*
* @return array testing scenarios
*/
public function add_section_provider(): array {
return array_merge(
$this->add_section_provider_helper('update'),
$this->add_section_provider_helper('create'),
$this->add_section_provider_helper('delete'),
);
}
/**
* Helper for add_section_provider scenarios.
*
* @param string $action the action to perform
* @return array testing scenarios
*/
private function add_section_provider_helper(string $action): array {
// Delete does not depends on user permissions.
if ($action == 'delete') {
$studentsections = [0, 1, 2];
} else {
$studentsections = [0, 1];
}
return [
"$action admin role" => [
'action' => $action,
'role' => 'admin',
'expected' => [0, 1, 2],
],
"$action teacher role" => [
'action' => $action,
'role' => 'editingteacher',
'expected' => [0, 1, 2],
],
"$action student role" => [
'action' => $action,
'role' => 'student',
'expected' => $studentsections,
],
];
}
/**
* Add track about a section state update.
*
* @dataProvider add_cm_provider
* @covers ::add_cm_update
* @covers ::add_cm_create
* @covers ::add_cm_delete
*
* @param string $action the action name
* @param string $role the user role name
* @param array $expected the expected results
*/
public function test_add_cm(string $action, string $role, array $expected): void {
global $PAGE, $DB;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course(['numsections' => 2, 'format' => 'topics']);
// Set section 2 hidden.
set_section_visible($course->id, 2, 0);
// Create 2 activities on each section.
$activities = [];
$activities[] = $this->getDataGenerator()->create_module(
'book',
['course' => $course->id],
['section' => 1, 'visible' => true]
);
$activities[] = $this->getDataGenerator()->create_module(
'book',
['course' => $course->id],
['section' => 1, 'visible' => false]
);
$activities[] = $this->getDataGenerator()->create_module(
'book',
['course' => $course->id],
['section' => 2, 'visible' => true]
);
$activities[] = $this->getDataGenerator()->create_module(
'book',
['course' => $course->id],
['section' => 2, 'visible' => false]
);
// Create and enrol user using given role.
if ($role == 'admin') {
$this->setAdminUser();
} else {
$user = $this->getDataGenerator()->create_user();
if ($role != 'unenroled') {
$this->getDataGenerator()->enrol_user($user->id, $course->id, $role);
}
$this->setUser($user);
}
// Initialise stateupdates.
$format = course_get_format($course);
$updates = new stateupdates($format);
$modinfo = $format->get_modinfo();
// Get the expected export.
$renderer = $format->get_renderer($PAGE);
$stateclass = $format->get_output_classname("cm_format\state");
// Execute method for both sections.
$method = "add_cm_{$action}";
foreach ($activities as $activity) {
$updates->$method($activity->cmid);
}
$updatelist = $updates->jsonSerialize();
$this->assertCount(count($expected), $updatelist);
foreach ($expected as $cmnum) {
$activity = $activities[$cmnum];
$cm = $modinfo->get_cm($activity->cmid);
$section = $modinfo->get_section_info($cm->sectionnum);
$currentstate = new $stateclass($format, $section, $cm);
$expected = $currentstate->export_for_template($renderer);
$update = $this->find_update($updatelist, $action, 'cm', $cm->id);
$this->assertEquals($action, $update->action);
$this->assertEquals('cm', $update->name);
// Delete does not provide all fields.
if ($action == 'delete') {
$this->assertEquals($cm->id, $update->fields->id);
} else {
$this->assertEquals($expected, $update->fields);
}
}
}
/**
* Data provider for test_add_section.
*
* @return array testing scenarios
*/
public function add_cm_provider(): array {
return array_merge(
$this->add_cm_provider_helper('update'),
$this->add_cm_provider_helper('create'),
$this->add_cm_provider_helper('delete'),
);
}
/**
* Helper for add_cm_provider scenarios.
*
* @param string $action the action to perform
* @return array testing scenarios
*/
private function add_cm_provider_helper(string $action): array {
// Delete does not depends on user permissions.
if ($action == 'delete') {
$studentcms = [0, 1, 2, 3];
} else {
$studentcms = [0];
}
return [
"$action admin role" => [
'action' => $action,
'role' => 'admin',
'expected' => [0, 1, 2, 3],
],
"$action teacher role" => [
'action' => $action,
'role' => 'editingteacher',
'expected' => [0, 1, 2, 3],
],
"$action student role" => [
'action' => $action,
'role' => 'student',
'expected' => $studentcms,
],
];
}
}

View file

@ -47,6 +47,7 @@ renderer and course format renderer:
compatibility (to not break third-party plugins without it), legacy_format_renderer has been created and will be used when
course formats don't have their own renderer.
* New external core_course\external\get_state returns current state information for a given course.
* New external function core_course_update_course runs given action to edit course status.
=== 3.11 ===
* A new callback xxx_coursemodule_definition_after_data that allows plugins to extend activity forms after the data is set.

View file

@ -757,7 +757,9 @@ $string['emojicategoryrecent'] = 'Recent';
$string['emojicategorysmileysemotion'] = 'Smileys & emotion';
$string['emojicategorysymbols'] = 'Symbols';
$string['emojicategorytravelplaces'] = 'Travel & places';
$string['emptycmids'] = 'Empty course module ids';
$string['emptydragdropregion'] = 'empty region';
$string['emptysectionids'] = 'Empty section ids';
$string['enable'] = 'Enable';
$string['encryptedcode'] = 'Encrypted code';
$string['enddate'] = 'Course end date';
@ -2146,6 +2148,8 @@ $string['turneditingoff'] = 'Turn editing off';
$string['turneditingon'] = 'Turn editing on';
$string['unauthorisedlogin'] = 'The user account "{$a}" is not available on this site';
$string['undecided'] = 'Undecided';
$string['unexistingcmid'] = 'Course module id not found';
$string['unexistingsectionid'] = 'Course section id not found';
$string['unfinished'] = 'Unfinished';
$string['unknowncategory'] = 'Unknown category';
$string['unknownerror'] = 'Unknown error';

View file

@ -514,6 +514,14 @@ $functions = array(
'type' => 'read',
'ajax' => true,
],
'core_course_update_course' => [
'classname' => 'core_course\external\update_course',
'methodname' => 'execute',
'description' => 'Update course contents.',
'type' => 'write',
'ajax' => true,
'capabilities' => 'moodle/course:sectionvisibility, moodle/course:activityvisibility',
],
'core_course_edit_module' => array(
'classname' => 'core_course_external',
'methodname' => 'edit_module',

View file

@ -92,6 +92,12 @@ class course_modinfo {
*/
private $sections;
/**
* Array from section id => section num.
* @var array
*/
private $sectionids;
/**
* Array from int (cm id) => cm_info object
* @var cm_info[]
@ -330,6 +336,24 @@ class course_modinfo {
return $this->sectioninfo[$sectionnumber];
}
/**
* Gets data about specific section ID.
* @param int $sectionid ID (not number) of section
* @param int $strictness Use MUST_EXIST to throw exception if it doesn't
* @return section_info|null Information for numbered section or null if not found
*/
public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING): ?section_info {
if (!isset($this->sectionids[$sectionid])) {
if ($strictness === MUST_EXIST) {
throw new moodle_exception('sectionnotexist');
} else {
return null;
}
}
return $this->get_section_info($this->sectionids[$sectionid], $strictness);
}
/**
* Static cache for generated course_modinfo instances
*
@ -469,6 +493,7 @@ class course_modinfo {
// Set initial values
$this->userid = $userid;
$this->sections = array();
$this->sectionids = [];
$this->cms = array();
$this->instances = array();
$this->groups = null;
@ -540,6 +565,7 @@ class course_modinfo {
// Expand section objects
$this->sectioninfo = array();
foreach ($coursemodinfo->sectioncache as $number => $data) {
$this->sectionids[$data->id] = $number;
$this->sectioninfo[$number] = new section_info($data, $number, null, null,
$this, null);
}

View file

@ -33,7 +33,7 @@ require_once($CFG->libdir . '/modinfolib.php');
* @copyright 2012 Andrew Davis
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_modinfolib_testcase extends advanced_testcase {
class modinfolib_test extends advanced_testcase {
public function test_section_info_properties() {
global $DB, $CFG;
@ -919,4 +919,86 @@ class core_modinfolib_testcase extends advanced_testcase {
list($course, $cm) = get_course_and_cm_from_cmid($hiddenpage->cmid, 'page', 0, $manager->id);
$this->assertTrue($cm->uservisible);
}
/**
* Test test_get_section_info_by_id method
*
* @dataProvider get_section_info_by_id_provider
* @covers ::get_section_info_by_id
*
* @param int $sectionnum the section number
* @param int $strictness the search strict mode
* @param bool $expectnull if the function will return a null
* @param bool $expectexception if the function will throw an exception
*/
public function test_get_section_info_by_id(
int $sectionnum,
int $strictness = IGNORE_MISSING,
bool $expectnull = false,
bool $expectexception = false
) {
global $DB;
$this->resetAfterTest();
// Create a course with 4 sections.
$course = $this->getDataGenerator()->create_course(['numsections' => 4]);
// Index sections.
$sectionindex = [];
$modinfo = get_fast_modinfo($course);
$allsections = $modinfo->get_section_info_all();
foreach ($allsections as $section) {
$sectionindex[$section->section] = $section->id;
}
if ($expectexception) {
$this->expectException(moodle_exception::class);
}
$sectionid = $sectionindex[$sectionnum] ?? -1;
$section = $modinfo->get_section_info_by_id($sectionid, $strictness);
if ($expectnull) {
$this->assertNull($section);
} else {
$this->assertEquals($sectionid, $section->id);
$this->assertEquals($sectionnum, $section->section);
}
}
/**
* Data provider for test_get_section_info_by_id().
*
* @return array
*/
public function get_section_info_by_id_provider() {
return [
'Valid section id' => [
'sectionnum' => 1,
'strictness' => IGNORE_MISSING,
'expectnull' => false,
'expectexception' => false,
],
'Section zero' => [
'sectionnum' => 0,
'strictness' => IGNORE_MISSING,
'expectnull' => false,
'expectexception' => false,
],
'invalid section ignore missing' => [
'sectionnum' => -1,
'strictness' => IGNORE_MISSING,
'expectnull' => true,
'expectexception' => false,
],
'invalid section must exists' => [
'sectionnum' => -1,
'strictness' => MUST_EXIST,
'expectnull' => false,
'expectexception' => true,
],
];
}
}