This commit is contained in:
Sara Arjona 2024-03-13 08:41:54 +01:00
commit 6c3ad2a841
No known key found for this signature in database
5 changed files with 541 additions and 1 deletions

View File

@ -0,0 +1,124 @@
<?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 core_role\reportbuilder\datasource;
use core\reportbuilder\local\entities\context;
use core_reportbuilder\datasource;
use core_reportbuilder\local\entities\user;
use core_role\reportbuilder\local\entities\{role, role_assignment};
/**
* Roles datasource
*
* @package core_role
* @copyright 2024 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class roles extends datasource {
/**
* Return user friendly name of the report source
*
* @return string
*/
public static function get_name(): string {
return get_string('roles', 'core_role');
}
/**
* Initialise report
*/
protected function initialise(): void {
$contextentity = new context();
$contextalias = $contextentity->get_table_alias('context');
$roleentity = new role();
$rolealias = $roleentity->get_table_alias('role');
// Role table.
$this->add_entity($roleentity->set_table_alias('context', $contextalias));
$this->set_main_table('role', $rolealias);
// Join role assignments.
$roleassignmententity = new role_assignment();
$roleassignmentalias = $roleassignmententity->get_table_alias('role_assignments');
$this->add_entity($roleassignmententity);
$this->add_join("JOIN {role_assignments} {$roleassignmentalias} ON {$roleassignmentalias}.roleid = {$rolealias}.id");
// Join context.
$this->add_entity($contextentity);
$this->add_join("LEFT JOIN {context} {$contextalias} ON {$contextalias}.id = {$roleassignmentalias}.contextid");
// Join user.
$userentity = new user();
$useralias = $userentity->get_table_alias('user');
$this->add_entity($userentity
->add_join("LEFT JOIN {user} {$useralias} ON {$useralias}.id = {$roleassignmentalias}.userid"));
$this->add_all_from_entities();
}
/**
* Return the columns that will be added to the report upon creation
*
* @return string[]
*/
public function get_default_columns(): array {
return [
'context:link',
'role:originalname',
'user:fullnamewithlink',
];
}
/**
* Return the column sorting that will be added to the report upon creation
*
* @return int[]
*/
public function get_default_column_sorting(): array {
return [
'context:link' => SORT_ASC,
'role:originalname' => SORT_ASC,
'user:fullnamewithlink' => SORT_ASC,
];
}
/**
* Return the filters that will be added to the report upon creation
*
* @return string[]
*/
public function get_default_filters(): array {
return [
'context:level',
'role:name',
'user:fullname',
];
}
/**
* Return the conditions that will be added to the report upon creation
*
* @return string[]
*/
public function get_default_conditions(): array {
return [];
}
}

View File

@ -14,6 +14,8 @@
// 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 core_role\reportbuilder\local\entities;
use context;
@ -97,7 +99,13 @@ class role extends base {
->set_type(column::TYPE_TEXT)
->add_fields("{$rolealias}.name, {$rolealias}.shortname, {$rolealias}.id, {$contextalias}.id AS contextid")
->add_fields(context_helper::get_preload_record_columns_sql($contextalias))
->set_is_sortable(true, ["CASE WHEN {$rolealias}.name = '' THEN {$rolealias}.shortname ELSE {$rolealias}.name END"])
// The sorting is on name, unless empty (determined by single space - thanks Oracle) then we use shortname.
->set_is_sortable(true, [
"CASE WHEN " . $DB->sql_concat("{$rolealias}.name", "' '") . " = ' '
THEN {$rolealias}.shortname
ELSE {$rolealias}.name
END",
])
->set_callback(static function($name, stdClass $role): string {
if ($name === null) {
return '';
@ -109,6 +117,30 @@ class role extends base {
return role_get_name($role, $context, ROLENAME_BOTH);
});
// Original name column.
$columns[] = (new column(
'originalname',
new lang_string('roleoriginalname', 'core_role'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_TEXT)
->add_fields("{$rolealias}.name, {$rolealias}.shortname")
// The sorting is on name, unless empty (determined by single space - thanks Oracle) then we use shortname.
->set_is_sortable(true, [
"CASE WHEN " . $DB->sql_concat("{$rolealias}.name", "' '") . " = ' '
THEN {$rolealias}.shortname
ELSE {$rolealias}.name
END",
])
->set_callback(static function($name, stdClass $role): string {
if ($name === null) {
return '';
}
return role_get_name($role, null, ROLENAME_ORIGINAL);
});
// Short name column.
$columns[] = (new column(
'shortname',

View File

@ -0,0 +1,143 @@
<?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 core_role\reportbuilder\local\entities;
use lang_string;
use core_reportbuilder\local\entities\base;
use core_reportbuilder\local\filters\date;
use core_reportbuilder\local\helpers\format;
use core_reportbuilder\local\report\{column, filter};
/**
* Role assignment entity
*
* @package core_role
* @copyright 2024 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class role_assignment extends base {
/**
* Database tables that this entity uses
*
* @return string[]
*/
protected function get_default_tables(): array {
return [
'role_assignments',
];
}
/**
* The default title for this entity
*
* @return lang_string
*/
protected function get_default_entity_title(): lang_string {
return new lang_string('roleassignment', 'core_role');
}
/**
* Initialise the entity
*
* @return base
*/
public function initialise(): base {
$columns = $this->get_all_columns();
foreach ($columns as $column) {
$this->add_column($column);
}
// All the filters defined by the entity can also be used as conditions.
$filters = $this->get_all_filters();
foreach ($filters as $filter) {
$this
->add_filter($filter)
->add_condition($filter);
}
return $this;
}
/**
* Returns list of all available columns
*
* @return column[]
*/
protected function get_all_columns(): array {
$raalias = $this->get_table_alias('role_assignments');
// Time modified column.
$columns[] = (new column(
'timemodified',
new lang_string('timemodified', 'core_reportbuilder'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_TIMESTAMP)
->add_field("{$raalias}.timemodified")
->set_is_sortable(true)
->set_callback([format::class, 'userdate']);
// Component column.
$columns[] = (new column(
'component',
new lang_string('plugin'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_TEXT)
->add_field("{$raalias}.component")
->set_is_sortable(true);
// Item ID column.
$columns[] = (new column(
'itemid',
new lang_string('pluginitemid'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_INTEGER)
->add_field("{$raalias}.itemid")
->set_is_sortable(true);
return $columns;
}
/**
* Return list of all available filters
*
* @return filter[]
*/
protected function get_all_filters(): array {
$raalias = $this->get_table_alias('role_assignments');
// Time modified filter.
$filters[] = (new filter(
date::class,
'timemodified',
new lang_string('timemodified', 'core_reportbuilder'),
$this->get_entity_name(),
"{$raalias}.timemodified"
))
->add_joins($this->get_joins());
return $filters;
}
}

View File

@ -0,0 +1,239 @@
<?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 core_role\reportbuilder\datasource;
use core\context\course;
use core_reportbuilder_generator;
use core_reportbuilder_testcase;
use core_reportbuilder\local\filters\{date, select, text};
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once("{$CFG->dirroot}/reportbuilder/tests/helpers.php");
/**
* Unit tests for roles datasource
*
* @package core_role
* @covers \core_role\reportbuilder\datasource\roles;
* @copyright 2024 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class roles_test extends core_reportbuilder_testcase {
/**
* Test default datasource
*/
public function test_datasource_default(): void {
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$context = course::instance($course->id);
$studentone = $this->getDataGenerator()->create_and_enrol($course, 'student', ['firstname' => 'Zoe']);
$studenttwo = $this->getDataGenerator()->create_and_enrol($course, 'student', ['firstname' => 'Amy']);
$manager = $this->getDataGenerator()->create_and_enrol($course, 'manager');
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report(['name' => 'Roles', 'source' => roles::class, 'default' => 1]);
$content = $this->get_custom_report_content($report->get('id'));
$this->assertCount(3, $content);
// Default columns are context link, original role name and user link. Sorted by each.
[$contextlink, $rolename, $userlink] = array_values($content[0]);
$this->assertStringContainsString($context->get_context_name(), $contextlink);
$this->assertEquals('Manager', $rolename);
$this->assertStringContainsString(fullname($manager), $userlink);
[$contextlink, $rolename, $userlink] = array_values($content[1]);
$this->assertStringContainsString($context->get_context_name(), $contextlink);
$this->assertEquals('Student', $rolename);
$this->assertStringContainsString(fullname($studenttwo), $userlink);
[$contextlink, $rolename, $userlink] = array_values($content[2]);
$this->assertStringContainsString($context->get_context_name(), $contextlink);
$this->assertEquals('Student', $rolename);
$this->assertStringContainsString(fullname($studentone), $userlink);
}
/**
* Test datasource columns that aren't added by default
*/
public function test_datasource_non_default_columns(): void {
global $DB;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$context = course::instance($course->id);
// Create an alias for our role.
$roleid = $DB->get_field('role', 'id', ['shortname' => 'manager']);
$DB->insert_record('role_names', (object) [
'contextid' => $context->id,
'roleid' => $roleid,
'name' => 'Moocher',
]);
$manager = $this->getDataGenerator()->create_user();
$this->getDataGenerator()->enrol_user($manager->id, $course->id, $roleid);
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report(['name' => 'Roles', 'source' => roles::class, 'default' => 0]);
// Role.
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role:name']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role:shortname']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role:description']);
// Role assignment.
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role_assignment:timemodified']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role_assignment:component']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role_assignment:itemid']);
$content = $this->get_custom_report_content($report->get('id'));
$this->assertCount(1, $content);
[$rolename, $roleshortname, $roledescription, $timemodified, $component, $itemid] = array_values($content[0]);
// Role.
$this->assertEquals('Moocher (Manager)', $rolename);
$this->assertEquals('manager', $roleshortname);
$this->assertEquals('Managers can access courses and modify them, but usually do not participate in them.',
$roledescription);
// Role assignment.
$this->assertNotEmpty($timemodified);
$this->assertEquals('', $component);
$this->assertEquals(0, $itemid);
}
/**
* Data provider for {@see test_datasource_filters}
*
* @return array[]
*/
public static function datasource_filters_provider(): array {
global $DB;
return [
// Role.
'Filter role name' => ['role:name', [
'role:name_operator' => select::EQUAL_TO,
'role:name_value' => $DB->get_field('role', 'id', ['shortname' => 'student']),
], true],
'Filter role name (no match)' => ['role:name', [
'role:name_operator' => select::EQUAL_TO,
'role:name_value' => -1,
], false],
// Role assignment.
'Filter role assignment time modified' => ['role_assignment:timemodified', [
'role_assignment:timemodified_operator' => date::DATE_RANGE,
'role_assignment:timemodified_from' => 1622502000,
], true],
'Filter role assignment time modified (no match)' => ['role_assignment:timemodified', [
'role_assignment:timemodified_operator' => date::DATE_RANGE,
'role_assignment:timemodified_to' => 1622502000,
], false],
// Context.
'Filter context level' => ['context:level', [
'context:level_operator' => select::EQUAL_TO,
'context:level_value' => CONTEXT_COURSE,
], true],
'Filter context level (no match)' => ['context:level', [
'context:level_operator' => select::EQUAL_TO,
'context:level_value' => CONTEXT_COURSECAT,
], false],
// User.
'Filter user firstname' => ['user:firstname', [
'user:firstname_operator' => text::IS_EQUAL_TO,
'user:firstname_value' => 'Zoe',
], true],
'Filter user firstname (no match)' => ['user:firstname', [
'user:firstname_operator' => text::IS_EQUAL_TO,
'user:firstname_value' => 'Amy',
], false],
];
}
/**
* Test datasource filters
*
* @param string $filtername
* @param array $filtervalues
* @param bool $expectmatch
*
* @dataProvider datasource_filters_provider
*/
public function test_datasource_filters(
string $filtername,
array $filtervalues,
bool $expectmatch,
): void {
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$this->getDataGenerator()->create_and_enrol($course, 'student', ['firstname' => 'Zoe']);
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
// Create report containing single column, and given filter.
$report = $generator->create_report(['name' => 'Roles', 'source' => roles::class, 'default' => 0]);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'role:shortname']);
// Add filter, set it's values.
$generator->create_filter(['reportid' => $report->get('id'), 'uniqueidentifier' => $filtername]);
$content = $this->get_custom_report_content($report->get('id'), 0, $filtervalues);
if ($expectmatch) {
$this->assertCount(1, $content);
$this->assertEquals('student', reset($content[0]));
} else {
$this->assertEmpty($content);
}
}
/**
* Stress test datasource
*
* In order to execute this test PHPUNIT_LONGTEST should be defined as true in phpunit.xml or directly in config.php
*/
public function test_stress_datasource(): void {
if (!PHPUNIT_LONGTEST) {
$this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
}
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$this->getDataGenerator()->create_and_enrol($course);
$this->datasource_stress_test_columns(roles::class);
$this->datasource_stress_test_columns_aggregation(roles::class);
$this->datasource_stress_test_conditions(roles::class, 'role:shortname');
}
}

View File

@ -404,6 +404,7 @@ $string['risks'] = 'Risks';
$string['roleallowheader'] = 'Allow role:';
$string['roleallowinfo'] = 'Select a role to be added to the list of allowed roles in context "{$a->context}", capability "{$a->cap}":';
$string['role:assign'] = 'Assign roles to users';
$string['roleassignment'] = 'Role assignment';
$string['roleassignments'] = 'Role assignments';
$string['roledefinitions'] = 'Role definitions';
$string['rolefullname'] = 'Role name';
@ -411,6 +412,7 @@ $string['roleincontext'] = '{$a->role} in {$a->context}';
$string['role:manage'] = 'Create and manage roles';
$string['role:override'] = 'Override permissions for others';
$string['role:review'] = 'Review permissions for others';
$string['roleoriginalname'] = 'Original name';
$string['roleprohibitheader'] = 'Prohibit role';
$string['roleprohibitinfo'] = 'Select a role to be added to the list of prohibited roles in context "{$a->context}", capability "{$a->cap}":';
$string['rolerisks'] = 'Role risks';