Spaces:
Runtime error
Runtime error
File size: 1,333 Bytes
ae8c95b 7ffb6c1 ae8c95b 7ffb6c1 ae8c95b 7ffb6c1 ae8c95b 7ffb6c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <?php
declare(strict_types=1);
use Psr\Log\LoggerInterface;
class AppConfig
{
private LoggerInterface $logger;
private array $config;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
$this->loadConfig();
}
private function loadConfig(): void
{
try {
$configFile = new SplFileObject(__DIR__ . '/../config/config.json', 'r');
$configContents = $configFile->fread($configFile->getSize());
$this->config = json_decode($configContents, true);
} catch (\Exception $exception) {
$this->logger->error('Failed to load the configuration file.', [
'exception' => $exception
]);
throw $exception;
}
}
public function getApiKey(string $className): string
{
if (!isset($this->config[$className])) {
$errorMessage = "API keys not found for class {$className}.";
$this->logger->error($errorMessage);
throw new \InvalidArgumentException($errorMessage);
}
$keys = $this->config[$className];
$keyIndex = array_rand($keys);
$selectedKey = $keys[$keyIndex];
$this->logger->info("Using {$className} API key: {$selectedKey}");
return $selectedKey;
}
}
|