107 lines
3.1 KiB
PHP
107 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Services;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
/**
|
|
* 统一解析上游数据源定义,避免业务代码直接拼接配置路径。
|
|
*/
|
|
class UpstreamSourceRegistry
|
|
{
|
|
public function __construct(
|
|
private readonly UpstreamStoredConfiguration $storedConfiguration,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @return array{key:string,label:string,config:string}
|
|
*/
|
|
public function definition(string $source): array
|
|
{
|
|
$source = strtolower(trim($source));
|
|
|
|
if ($source === '' || ! preg_match('/^[a-z0-9_-]+$/', $source)) {
|
|
throw new InvalidArgumentException('上游数据源标识不合法。');
|
|
}
|
|
|
|
$definition = config('upstreams.sources.' . $source);
|
|
|
|
if (! is_array($definition)) {
|
|
throw new InvalidArgumentException('未登记的上游数据源:' . $source);
|
|
}
|
|
|
|
$configKey = trim((string) ($definition['config'] ?? ''));
|
|
|
|
if ($configKey === '' || ! preg_match('/^[a-z0-9_.-]+$/i', $configKey)) {
|
|
throw new InvalidArgumentException('上游数据源配置路径不合法:' . $source);
|
|
}
|
|
|
|
return [
|
|
'key' => $source,
|
|
'label' => trim((string) ($definition['label'] ?? $source)) ?: $source,
|
|
'config' => $configKey,
|
|
];
|
|
}
|
|
|
|
public function value(string $source, string $path, mixed $default = null): mixed
|
|
{
|
|
$definition = $this->definition($source);
|
|
$suffix = trim($path, '.');
|
|
$key = $definition['config'] . ($suffix === '' ? '' : '.' . $suffix);
|
|
$configured = config($key, $default);
|
|
|
|
if ($this->usesLocalConfiguration()) {
|
|
return $configured;
|
|
}
|
|
|
|
if ($suffix === 'connection') {
|
|
return $this->connection($definition['key'], (array) $configured);
|
|
}
|
|
|
|
// Hosts and credentials come from the shared record, while the ODBC
|
|
// driver must match the operating system that runs this application.
|
|
if ($suffix === 'connection.odbc_driver' && trim((string) $configured) !== '') {
|
|
return $configured;
|
|
}
|
|
|
|
return $this->storedConfiguration->value($definition['key'], $suffix, $configured);
|
|
}
|
|
|
|
public function enabled(string $source): bool
|
|
{
|
|
return (bool) $this->value($source, 'enabled', false);
|
|
}
|
|
|
|
private function usesLocalConfiguration(): bool
|
|
{
|
|
return (bool) config('upstreams.local_configuration.enabled', false);
|
|
}
|
|
|
|
private function connection(string $source, array $configured): array
|
|
{
|
|
$fields = array_values(array_unique(array_merge(array_keys($configured), [
|
|
'host',
|
|
'port',
|
|
'database',
|
|
'username',
|
|
'password',
|
|
'odbc_driver',
|
|
'tds_version',
|
|
'connect_timeout',
|
|
'query_timeout',
|
|
])));
|
|
$resolved = $configured;
|
|
|
|
foreach ($fields as $field) {
|
|
$resolved[$field] = $this->value(
|
|
$source,
|
|
'connection.' . $field,
|
|
$configured[$field] ?? null,
|
|
);
|
|
}
|
|
|
|
return $resolved;
|
|
}
|
|
}
|