CaiWuXiTong/app/Console/Commands/ConnectTeamSystemDatabase.php

76 lines
3.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Console\Commands;
use App\Utilities\SystemDatabaseConfiguration;
use App\Utilities\TeamSystemDatabaseProfile;
use Illuminate\Console\Command;
use Throwable;
class ConnectTeamSystemDatabase extends Command
{
protected $signature = 'system-database:connect-team {--password-stdin : 从标准输入读取首次接入密码,不使用命令行明文参数}';
protected $description = '本地开发环境使用已有密码跟随最新团队连接资料,不迁移或写入共享数据库';
public function handle(SystemDatabaseConfiguration $configuration, TeamSystemDatabaseProfile $profile): int
{
if (! app()->environment(['local', 'development', 'testing'])) {
$this->error('此命令仅用于本地开发环境,不修改生产服务器连接。');
return self::FAILURE;
}
$current = $configuration->current();
$password = $this->option('password-stdin')
? rtrim((string) fgets(STDIN, 1002), "\r\n")
: (string) ($current['password'] ?? '');
try {
$settings = $profile->settings($password);
} catch (Throwable) {
$this->warn('本机尚未保存有效的团队密码。请在系统数据库页面输入一次密码;已有配置未修改,无需另配上游账号。');
return VerifySystemDatabase::EXIT_SHARED_NOT_CONFIGURED;
}
try {
// 只探测最新端点,不先连接可能已停用的旧服务器。
$result = $configuration->probe($settings);
$settings['prefix'] = $result['prefix'];
if ($this->matches($current, $settings)) {
$this->info('本机已连接最新团队系统数据库,业务镜像共用此连接。');
return self::SUCCESS;
}
} catch (Throwable) {
$this->error('最新团队数据库接入未通过验证,原配置已保留。请检查网络、TLS和共享库访问权限;不要改填上游账号。');
return self::FAILURE;
}
try {
$configuration->persist($settings);
} catch (Throwable) {
$this->error('本机配置保存或复核失败。请核对私有配置备份和系统连接状态;不要仅修改运行模式或绕过验证。');
return self::FAILURE;
}
$this->info('已备份并更新本机系统库、业务镜像库连接。请重新登录;未迁移或同步业务数据。');
return self::SUCCESS;
}
private function matches(array $current, array $settings): bool
{
foreach (['host', 'port', 'database', 'username', 'password', 'prefix', 'tls_required', 'tls_verify_server_cert', 'tls_ca'] as $key) {
if (($current[$key] ?? null) != ($settings[$key] ?? null)) return false;
}
$mirror = (array) config('database.connections.business_mirror');
return ($current['mode'] ?? '') === 'shared'
&& config('upstreams.stored_configuration.enabled', false)
&& ! config('upstreams.local_configuration.enabled', false)
&& data_get($mirror, 'read.host.0') === $settings['host']
&& data_get($mirror, 'write.host.0') === $settings['host']
&& (int) ($mirror['port'] ?? 0) === (int) $settings['port']
&& ($mirror['database'] ?? '') === $settings['mirror_database']
&& ($mirror['username'] ?? '') === $settings['username']
&& ($mirror['password'] ?? '') === $settings['password']
&& empty($mirror['unix_socket']);
}
}