Passed
Pull Request — master (#6087)
by
unknown
07:41
created

AiProviderFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 39
rs 10
c 1
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getProvider() 0 9 2
A __construct() 0 22 5
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Service\AI;
8
9
use Chamilo\CoreBundle\Settings\SettingsManager;
10
use Symfony\Contracts\HttpClient\HttpClientInterface;
11
use InvalidArgumentException;
12
13
class AiProviderFactory
14
{
15
    private array $providers;
16
    private string $defaultProvider;
17
18
    public function __construct(HttpClientInterface $httpClient, SettingsManager $settingsManager)
19
    {
20
        // Get AI providers from settings
21
        $configJson = $settingsManager->getSetting('ai_helpers.ai_providers', true);
22
        $config = json_decode($configJson, true) ?? [];
23
24
        // Get the first available provider as default
25
        $this->defaultProvider = array_key_first($config) ?? 'openai';
26
27
        // Initialize AI providers dynamically
28
        $this->providers = [];
29
        foreach ($config as $providerName => $providerConfig) {
30
            if ($providerName === 'openai') {
31
                $this->providers[$providerName] = new OpenAiProvider($httpClient, $settingsManager);
32
            } elseif ($providerName === 'deepseek') {
33
                $this->providers[$providerName] = new DeepSeekAiProvider($httpClient, $settingsManager);
34
            }
35
        }
36
37
        // Ensure the selected default provider exists
38
        if (!isset($this->providers[$this->defaultProvider])) {
39
            throw new InvalidArgumentException("The default AI provider '{$this->defaultProvider}' is not configured properly.");
40
        }
41
    }
42
43
    public function getProvider(string $provider = null): AiProviderInterface
44
    {
45
        $provider = $provider ?? $this->defaultProvider;
46
47
        if (!isset($this->providers[$provider])) {
48
            throw new InvalidArgumentException("AI Provider '$provider' is not supported.");
49
        }
50
51
        return $this->providers[$provider];
52
    }
53
}
54