| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Services\Integrations\AI; |
| 4 |
|
| 5 |
use FluentSupport\App\Services\Helper; |
| 6 |
use WP_Error; |
| 7 |
|
| 8 |
class AIProviderFactory |
| 9 |
{ |
| 10 |
private static $instance = null; |
| 11 |
|
| 12 |
private static $allowedProviders = ['openai', 'gemini', 'anthropic']; |
| 13 |
|
| 14 |
/** |
| 15 |
* @param string $provider |
| 16 |
* @param string $apiKey |
| 17 |
* @param string $model |
| 18 |
* @return BaseAIProvider|WP_Error |
| 19 |
*/ |
| 20 |
public static function make(string $provider, string $apiKey, string $model) |
| 21 |
{ |
| 22 |
switch ($provider) { |
| 23 |
case 'openai': |
| 24 |
return new Providers\OpenAIProvider($apiKey, $model); |
| 25 |
case 'gemini': |
| 26 |
return new Providers\GeminiProvider($apiKey, $model); |
| 27 |
case 'anthropic': |
| 28 |
return new Providers\AnthropicProvider($apiKey, $model); |
| 29 |
default: |
| 30 |
return new WP_Error('invalid_provider', __('Invalid AI provider.', 'fluent-support')); |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* @return BaseAIProvider|WP_Error |
| 36 |
*/ |
| 37 |
public static function makeFromSettings() |
| 38 |
{ |
| 39 |
if (self::$instance !== null) { |
| 40 |
return self::$instance; |
| 41 |
} |
| 42 |
|
| 43 |
$settings = Helper::getAIProviderSettings(); |
| 44 |
|
| 45 |
if (($settings['enabled'] ?? 'yes') === 'no') { |
| 46 |
return new WP_Error('ai_disabled', __('AI features are disabled.', 'fluent-support')); |
| 47 |
} |
| 48 |
|
| 49 |
$provider = $settings['provider'] ?? 'openai'; |
| 50 |
|
| 51 |
if (empty($settings['api_key'])) { |
| 52 |
return new WP_Error('no_api_key', __('No AI provider configured.', 'fluent-support')); |
| 53 |
} |
| 54 |
$instance = self::make($provider, $settings['api_key'], $settings['model'] ?? ''); |
| 55 |
|
| 56 |
if (!is_wp_error($instance)) { |
| 57 |
self::$instance = $instance; |
| 58 |
} |
| 59 |
|
| 60 |
return $instance; |
| 61 |
} |
| 62 |
|
| 63 |
public static function clearCache(): void |
| 64 |
{ |
| 65 |
self::$instance = null; |
| 66 |
} |
| 67 |
|
| 68 |
public static function getAllowedProviders(): array |
| 69 |
{ |
| 70 |
return self::$allowedProviders; |
| 71 |
} |
| 72 |
} |
| 73 |
|