MDL-84453 ai: simpler API for retrieving single provider record.

This commit is contained in:
Paul Holden 2025-02-06 21:28:27 +00:00
parent 139a0ad5f0
commit 3f6838b1b9
No known key found for this signature in database
GPG Key ID: A81A96D6045F6164
4 changed files with 41 additions and 6 deletions

View File

@ -388,12 +388,26 @@ class manager {
return $provider->with(id: $id);
}
/**
* Get single provider record according to the filter
*
* @param array $filter The filterable elements to get the record from
* @param int $strictness
* @return \stdClass|false
*/
public function get_provider_record(array $filter = [], int $strictness = IGNORE_MISSING): \stdClass|false {
return $this->db->get_record(
table: 'ai_providers',
conditions: $filter,
strictness: $strictness,
);
}
/**
* Get the provider records according to the filter.
*
* @param array|null $filter The filterable elements to get the records from.
* @return array
* @throws \dml_exception
* @return \stdClass[]
*/
public function get_provider_records(?array $filter = null): array {
return $this->db->get_records(

View File

@ -52,8 +52,7 @@ if ($provider) {
if ($id !== 0) { // If we have an id we are updating an existing provider instance.
$manager = \core\di::get(\core_ai\manager::class);
$providerrecord = $manager->get_provider_records(['id' => $id]);
$providerrecord = reset($providerrecord);
$providerrecord = $manager->get_provider_record(['id' => $id], MUST_EXIST);
$plugin = explode('\\', $providerrecord->provider);
$plugin = $plugin[0];

View File

@ -46,8 +46,7 @@ if (empty($returnurl)) {
$data['returnurl'] = $returnurl;
$manager = \core\di::get(\core_ai\manager::class);
$providerrecord = $manager->get_provider_records(['id' => $id]);
$providerrecord = reset($providerrecord);
$providerrecord = $manager->get_provider_record(['id' => $id], MUST_EXIST);
$actionconfig = json_decode($providerrecord->actionconfig, true, 512, JSON_THROW_ON_ERROR);
$actionconfig = $actionconfig[$action];

View File

@ -109,7 +109,30 @@ final class manager_test extends \advanced_testcase {
classname: $this::class,
name: 'dummy',
);
}
/**
* Test get_provider_record method
*/
public function test_get_provider_record(): void {
global $DB;
$this->resetAfterTest();
// Create a dummy provider record directly in the database.
$config = ['data' => 'goeshere'];
$record = new \stdClass();
$record->name = 'dummy1';
$record->provider = 'dummy';
$record->enabled = 1;
$record->config = json_encode($config);
$record->actionconfig = json_encode(['generate_text' => 1]);
$record->id = $DB->insert_record('ai_providers', $record);
$manager = \core\di::get(\core_ai\manager::class);
$provider = $manager->get_provider_record(['provider' => 'dummy']);
$this->assertEquals($record->id, $provider->id);
}
/**