Skip to content

Commit

Permalink
issue #116: add WS to delete and toggle rules
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitriim committed Dec 4, 2024
1 parent ba32823 commit e64dfa9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 17 deletions.
26 changes: 12 additions & 14 deletions classes/external/rules.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,28 +58,26 @@ public static function delete_rules_parameters(): external_function_parameters {
* @return array
*/
public static function delete_rules(array $ruleids): array {
global $DB;

self::validate_parameters(self::delete_rules_parameters(), ['ruleids' => $ruleids]);

$context = context_system::instance();
self::validate_context($context);
require_capability('tool/dynamic_cohorts:manage', $context);

// We would like to treat deletion for multiple rules as one operation.
// If one failed we would like to fail whole call and roll back.
$transaction = $DB->start_delegated_transaction();
try {
foreach ($ruleids as $ruleid) {
$rule = rule::get_record(['id' => (int) $ruleid]);
if (empty($rule)) {
throw new invalid_parameter_exception('Rule does not exist. ID: ' . $ruleid);
}
rule_manager::delete_rule($rule);
//$transaction->allow_commit();
// So let's check that all rules exist and then delete them.
// Otherwise throw an exception and fail whole WS call.
$rulestodelete = [];
foreach ($ruleids as $ruleid) {
$rule = rule::get_record(['id' => (int) $ruleid]);
if (empty($rule)) {
throw new invalid_parameter_exception('Rule does not exist. ID: ' . $ruleid);
}
} catch (throwable $ex) {
$transaction->rollback($ex);
$rulestodelete[] = $rule;
}

foreach ($rulestodelete as $rule) {
rule_manager::delete_rule($rule);
}

return [];
Expand Down
3 changes: 0 additions & 3 deletions tests/external/rules_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,6 @@ public function test_delete_rules_keep_rules_when_one_is_invalid() {

$this->assertCount(2, rule::get_records());

$this->expectException(\required_capability_exception::class);
$this->expectExceptionMessage('Rule does not exist. ID: 777');

try {
rules::delete_rules([$rule1->get('id'), $rule2->get('id'), 777]);
} catch (\invalid_parameter_exception $exception) {
Expand Down

0 comments on commit e64dfa9

Please sign in to comment.