signature = implode(' ', [ 'lsky:install', '{--connection=mysql : Database type}', '{--host=127.0.0.1 : Database connection address}', '{--port=3306 : Database connection port}', '{--database= : Database name}', '{--username=root : Database connection user name}', '{--password=root : Database connection password}', ]); parent::__construct(); } /** * Execute the console command. */ public function handle() { // 判断是否已经安装 if (file_exists(base_path('installed.lock'))) { $this->warn('Already installed. if you want to reinstall, please remove installed.lock file.'); return; } $driver = $this->option('connection'); $connection = "database.connections.{$driver}"; $options = [ 'connection' => $this->option('connection'), 'host' => $this->option('host'), 'port' => $this->option('port'), 'database' => $this->option('database'), 'username' => $this->option('username'), 'password' => $this->option('password'), ]; $configs = array_intersect_key($options, config($connection)); // 覆盖默认配置 Config::set($connection, array_merge(config($connection), $configs)); // 设置默认数据库驱动 Config::set('database.default', $driver); try { // 执行数据库迁移 Artisan::call('migrate:fresh', ['--force' => true]); // 填充数据 Artisan::call('db:seed', ['--force' => true, '--class' => 'InstallSeeder']); // 更新 env 文件 $replaces = collect($options)->transform(fn ($item, $key) => ['DB_'.strtoupper($key) => $item])->collapse(); file_put_contents($this->laravel->environmentFilePath(), preg_replace( $replaces->map(fn ($item, $key) => $this->replacementPattern($key, env($key, '')))->values()->toArray(), $replaces->map(fn ($item, $key) => "{$key}={$item}")->values()->toArray(), file_get_contents($this->laravel->environmentFilePath()) )); } catch (\Throwable $e) { $this->warn("Installation error!\n"); $this->error($e->getMessage()); return; } $this->info('Install success!'); } protected function replacementPattern(string $name, string $value): string { $escaped = preg_quote('='.$value, '/'); return "/^{$name}{$escaped}/m"; } }