feat: 添加统一数据库初始化命令,简化数据库迁移和种子填充流程;新增基础和演示数据填充器
This commit is contained in:
90
app/Console/Commands/LotteryDatabaseInitCommand.php
Normal file
90
app/Console/Commands/LotteryDatabaseInitCommand.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
final class LotteryDatabaseInitCommand extends Command
|
||||
{
|
||||
protected $signature = 'lottery:db-init
|
||||
{--fresh : 先执行 migrate:fresh,再初始化数据库}
|
||||
{--demo : 额外写入演示数据(生产环境默认关闭)}
|
||||
{--no-demo : 禁止写入演示数据}
|
||||
{--skip-auth-sync : 跳过后台权限注册表同步}';
|
||||
|
||||
protected $description = '统一初始化数据库:迁移/基线、基础种子、后台权限同步,以及非生产演示数据';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$isProduction = app()->environment('production');
|
||||
$seedDemo = $this->shouldSeedDemo($isProduction);
|
||||
$migrationCommand = (bool) $this->option('fresh') ? 'migrate:fresh' : 'migrate';
|
||||
|
||||
$this->components->info(sprintf(
|
||||
'开始数据库初始化:%s%s',
|
||||
$migrationCommand,
|
||||
$seedDemo ? ' + foundation seed + demo seed' : ' + foundation seed',
|
||||
));
|
||||
|
||||
$migrateExit = $this->call($migrationCommand, [
|
||||
'--force' => true,
|
||||
]);
|
||||
if ($migrateExit !== self::SUCCESS) {
|
||||
return $migrateExit;
|
||||
}
|
||||
|
||||
$foundationExit = $this->call('db:seed', [
|
||||
'--class' => 'Database\\Seeders\\FoundationSeeder',
|
||||
'--force' => true,
|
||||
]);
|
||||
if ($foundationExit !== self::SUCCESS) {
|
||||
return $foundationExit;
|
||||
}
|
||||
|
||||
if (! (bool) $this->option('skip-auth-sync')) {
|
||||
$authExit = $this->call('lottery:admin-auth-sync', [
|
||||
'--audit' => true,
|
||||
]);
|
||||
if ($authExit !== self::SUCCESS) {
|
||||
return $authExit;
|
||||
}
|
||||
}
|
||||
|
||||
if ($seedDemo) {
|
||||
if ($isProduction) {
|
||||
$this->components->error('production 环境禁止写入演示数据。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$demoExit = $this->call('db:seed', [
|
||||
'--class' => 'Database\\Seeders\\LocalDemoSeeder',
|
||||
'--force' => true,
|
||||
]);
|
||||
if ($demoExit !== self::SUCCESS) {
|
||||
return $demoExit;
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->components->info('数据库初始化完成。');
|
||||
$this->line(sprintf('环境:%s', app()->environment()));
|
||||
$this->line(sprintf('演示数据:%s', $seedDemo ? '已写入' : '未写入'));
|
||||
$this->line('统一入口命令:php artisan lottery:db-init');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function shouldSeedDemo(bool $isProduction): bool
|
||||
{
|
||||
if ((bool) $this->option('no-demo')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((bool) $this->option('demo')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ! $isProduction;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user